Dygraph is not defined, using Flask - flask

I am using flask and trying to get the dygraph sample to work. Here is the sample code (2nd example from the tutorial page: http://dygraphs.com/tutorial.html):
<html>
<head>
<script type="text/javascript"
src="dygraph-combined.js"></script>
</head>
<body>
<div id="graphdiv2"
style="width:500px; height:300px;"></div>
<script type="text/javascript">
g2 = new Dygraph(
document.getElementById("graphdiv2"),
"temperatures.csv", // path to CSV file
{} // options
);
</script>
</body>
</html>
Here is my Flask code (I'm trying to use render_template()):
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def render_plot():
return render_template('sample.html')
if __name__ == '__main__':
app.run()
When I run this through python firebug gives me the error "Dygraph is not defined." from the line g2 = new Dygraph(
Sample.html works in my folder, but it does not work when I try to access it from my url after running my flask code from python. My folders look like this:
FlaskStuff/main.py
FlaskStuff/templates/sample.html
FlaskStuff/templates/dygraph-combined.js (To load sample.html in my folder).
FlaskStuff/js/dygraph-combined.js
I am new to Flask. Similar answers did not help me to solve this problem.

Where is dygraph-combined.js located? It needs to be somewhere it can be served. You will most likely what to place it inside your static folder. It's a fairly common practice to group like files inside static (e.g., css, js).
Using this structure
static/
js/
dygraph-combined.js
you'll want to update sample.html as follows
<script type="text/javascript" src="{{ url_for('static', filename='js/dygraph-combined.js') }}"></script>
This will allow the Flask development server to serve the file. You'll also want to add a rule to your HTTP server to serve content from /static directly.

You will also have to do a similar thing for the temperature.csv file. (I've placed it in the static folder)
"{{ url_for('static', filename='temperatures.csv') }}", // path to CSV file

Related

Changing the favicon in Flask/Dash

Trying to get the favicon to load I have followed suggestions from the internet:
server = Flask(__name__, static_folder='static')
app = dash.Dash(external_stylesheets=external_stylesheets, server=server)
app.css.config.serve_locally = False
app.scripts.config.serve_locally = True
#server.route('/favicon.ico')
def favicon():
print('Server root path', server.root_path)
return send_from_directory(os.path.join(server.root_path, 'static'),
'dice.ico', mimetype='image/vnd.microsoft.icon')
...
app.run_server(debug=True)
If I browse to the favicon, I see it:
http://www.example.com/favicon.ico
However, when I browse to
http://www.example.com
I see the dash default icon with it's own description. How do I ensure my ownfavicon loads correctly?
To simply change the favicon all you need to do is to create a folder called assets next to your app.py and place your favicon.ico inside of that folder and it will work perfectly.
app.py:
import flask
import dash
import dash_html_components as html
server = flask.Flask(__name__)
#server.route('/')
def index():
return 'Hello Flask app'
app = dash.Dash(
__name__,
server=server,
routes_pathname_prefix='/dash/'
)
app.layout = html.Div("My Dash app")
if __name__ == '__main__':
app.run_server(debug=True)
Here is the docs link for more information: Dash docs
An alternative used in Dash is:
app = dash.Dash()
app._favicon = ("path_to_folder/(your_icon).co")
You can just put title="My Title" as an argument when establishing the Dash app instance. i.e.
app = dash.Dash(
__name__,
title="My Title",
server=server,
routes_pathname_prefix='/dash/'
)
Adding for the sake of completeness. Nowadays, it's recommended to use a bundle of icons with different resolutions to please different browsers and ensure the best picture quality. You can produce such a bundle with the help of, say, realfavicongenerator.net Or you simply might want to use a non-standard .png or .svg icon.
For that, you can subclass Dash and add your much desired link rel and meta tags to its interpolate_index method:
import dash
class CustomDash(dash.Dash):
def interpolate_index(self, **kwargs):
return '''
<!DOCTYPE html>
<html>
<head>
{metas}
<title>{title}</title>
<link rel="apple-touch-icon" sizes="180x180" href="assets/favicons/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="assets/favicons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="assets/favicons/favicon-16x16.png">
<link rel="manifest" href="assets/favicons/site.webmanifest">
<link rel="mask-icon" href="assets/favicons/safari-pinned-tab.svg" color="#5bbad5">
<meta name="msapplication-TileColor" content="#da532c">
<meta name="theme-color" content="#ffffff">
{css}
</head>
<body>
{app_entry}
<footer>
{config}
{scripts}
{renderer}
</footer>
</body>
</html>
'''.format(**kwargs)
app = CustomDash()
Do not forget to place the unzipped bundle into your assets/favicons subfolder!
You should create an "assets" folden and then update the "__favicon" property in your Dash app:
app._favicon = "favico.ico"
Even if OP's accepted answer doesn't work, refer to official document which says:
It is recommended to add name to the dash init to ensure the resources in the assets folder are loaded, eg: app = dash.Dash(name, meta_tags=[...]). When you run your application through some other command line (like the flask command or gunicorn/waitress), the main module will no longer be located where app.py is. By explicitly setting name, Dash will be able to locate the relative assets folder correctly.
Include __name__ in Dash object:
app = Dash(__name__)

Flask-Asset does not create correct url on template

I cannot figure out why Flask-CDN is not building my templates with the Amazon CloudFront url for my static files. Here is my setup:
1) Configure cdn domain and ask Flask-Assets to use cdn:
class AppConfig(BaseConfig):
DEBUG = False
FLASK_ASSETS_USE_CDN = True
CDN_DOMAIN = "mydomain.cloudfront.net"
2) The Flask app with the CDN object:
config_object = AppConfig
app = flask.Flask(config_object.PROJECT_NAME, static_folder='web/static')
app.config.from_object(config_object)
# Bundles are configured here (many of them!) to generate the app.js file
if config_object.DEBUG is False:
CDN(app)
app.run(host='0.0.0.0')
3) The template that uses the assets:
{% assets "js_app" %}
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
{% endassets %}
4) Finally, the html built by the server was:
<script type="text/javascript" src="/static/gen/app.js?40c12882"></script>
I'm wondering why the html doesn't contain my CDN domain, as it should have been generated like this:
<script type="text/javascript" src="http://mydomain.cloudfront.net/static/gen/app.js?40c12882"></script>
Thank you.
Ok. Found the problem. The latest version of Flask-Assets on pip (0.10) does not contain the CDN feature described on docs for current version, that is 0.10.

Django URL Conf unable to find javascript file

I am learning Django and as an example I am trying to implement a small site that serves static pages. I am using django.contrib.flatpages app for the same. As part of this, I have a javascript file located in a directory. I am referencing this javascript file in my html page. Accordingly, I have configured the URL pattern in my project's URL Conf file as follows:
url(r'^tinymce/(?P<path>.*)$','django.views.static.serve',{'document-root':'C:/RAKESH/djangowork/cms/cms/templates/admin/flatpages/flatpage/tinymce'}),
But when I try to load the html page, the javascript file doesn't seem to be loaded. The following is the referencing code in my html file:
<script type="text/javascript" src="/tinymce/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({
selector:'textarea'
});
</script>
Can someone help me fix this problem?
Thanks,
Rakesh.
Don't add an extra URLconf for that! Use the standard way in Django to serve static (non-cms-editable) files: https://docs.djangoproject.com/en/dev/howto/static-files/
Place the tinymce folder inside a static folder in your app folder, then use in your template:
<script type="text/javascript" src="{% static "/tinymce/tinymce.min.js" %}"></script>

How to import dajaxice?

I'm a nooby to django and I tried many hours to get a simple example of dajaxice running, but I don't seem to find the right way to look for the files.
I did and redid installation and tried to find answers in the numerous similar questions on stackoverflow like this one and this one.
I put {% dajaxice_js_import %} in the header of myapp_index.html which prints out as:
<script src="/static/dajaxice/dajaxice.core.js"
type="text/javascript" charset="utf-8"></script>
but it cannot find this file:
ImproperlyConfigured: The storage backend of the staticfiles finder doesn't have a valid location.
And the get fails:
GET /static/dajaxice/dajaxice.core.js HTTP/1.1" 500 59
Strangely enough dajax loads:
<script type="text/javascript"
src="{% static /static/dajax/jquery.dajax.core.js" %}"></script>
Here's my folder structure:
myproject
----manage.py
----myproject
--------settings.py
--------urls.py
----myapp
--------ajax.py
--------urls.py
--------templates
------------myapp_index.html
I also haven't really understood why we need two urls.py files, but somehow it seems to access myapp_index.html if I put
from django.views.generic.simple import direct_to_template
and then
url(r'^$', direct_to_template, {'template': 'myapp_index.html'}),
in myapp's url patterns.
I also tried uncountable filenames in
python manage.py findstatic dajaxice.core.js
but somehow it doesn't find dajaxice, even though dajaxice is installed and accepted in the settings.py file among the INSTALLED_APPS.
Also python manage.py collectstatic fails for the same reason, but if I understood correctly, I don't event have to make it run as long as I'm on a development server.
I guess I have some basic misunderstanding of the underlying structure. :(
I'm using the prepacked latest ubuntu packages:
django: 1.4.5,
dajaxice: 0.5.5
Thanks in advance for any hint!
here is the template file:
{% load static %}
{% load dajaxice_templatetags %}
<html>
<head>
<title>My base template</title>
{% dajaxice_js_import %}
<script type="text/javascript" src="{% static "/static/dajax/jquery.dajax.core.js" %}"></script>
<script type="text/javascript">
function my_js_callback(data){
alert(data.message);
}
Dajax;
Dajaxice;
</script>
</head>
...
<button onclick="Dajaxice.myproject.myapp.sayhello(my_js_callback);">Click here!</button>
I get no Django error, the page shows, but I get this in Firebug:
"NetworkError: 500 Internal Server Error - http://localhost:8000/static/dajaxice/dajaxice.core.js"
and this:
ReferenceError: Dajaxice is not defined
Dajaxice;
It seems that you've messed up your urls.conf. It should contain something like:
url(dajaxice_config.dajaxice_url, include('dajaxice.urls')),
Does it?
Also, the STATICFILES_FINDERS section of your settings.py file should include:
'dajaxice.finders.DajaxiceFinder',

Using Protovis with Django

I am trying to get Protovis working in my Django site. Here is my sample code:
<html>
<head>
<script type="text/javascript" src="protovis-r3.2.js"></script>
</head>
<body>
<script type="text/javascript+protovis">
new pv.Panel().width(150).height(150).anchor("center")
.add(pv.Label)
.text("Hello, world!")
.root.render();
</script>
{{ object.name }}
</body>
</html>
When I open this file directly in firefox, a Protovis 'Hello World' image is displayed toguether with the string "{{ object.name }}".
But when accessing the .html file template from my Django server, I only see the {{ object.name }} (the object's name printed out).
I haven't found similar issues so far, catering to Protovis use in Django.
If anyone has gotten it working or know what I am doing wrong, please let me know.
Thanks,
You've asked for the javascript file using src="protovis-r3.2.js"
When you look at the html file directly, your browser will look in the same directory as the .html file for a file called protovis-r3.2.js.
However, when you ask Django to serve this same page, it doesn't follow the same protocol. See this article for more information.
To get it to work:
Move the protovis-r.32.js file to a new directory: /path/to/my/django_site/static (where /path/to/my/django_site is the absolute path to the django app)
Configure urls.py with the line:
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/path/to/my/django_site/static'}),
Change the src attribute of the script tag in your html code to:
src="/static/protovis-r3.2.js"