Flask app can't find static files on AWS ECR + Fargate - amazon-web-services

I have flask app with next structure:
templates/
dashboard.html
static/
css/
styles.css
js/
main.js
Dockerfile
app.py
In app.py I just have one endpoint to serve main page.
app.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/home")
def dashboard():
return render_template('dashboard.html')
if __name__ == '__main__':
app.run(debug=True)
dashboard.html:
<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
</head>
<body>...</body>
<script type="text/javascript" src="{{url_for('static', filename='js/main.js')}}"></script>
</body>
</html>
The app is hosted on AWS ECR+Fargate ( I am not the person who did devops side).
The app works, but static files (js and css) are not loaded, error 404. What could I miss?

Related

Django url tags linking

i'm new into django. I created a project named marketbook, it has a main templates directory and an app called users. Inside my app (users) i have templates folder as well with a file called login.html (templates/users/login.html.
I want to link this login.html in my app to a link in my file (navbar.html) in my main templates director folder. what should be the url tag to use?
Log In
In the settings.py file, the TEMPLATES variable is set to the field: 'DIRS': ['templates']. This is so that you can find the main home.html template, which is located in the templates folder, which is located in the folder where the application folder is, the manage.py module.
start the server: python manage.py runserve
go to: http://localhost:8000/users/home/
press the button and go to: http://localhost:8000/users/navbar/
urls.py (urls application)
from django.urls import path
from .views import home, navbar
urlpatterns = [
path('home/', home),
path('navbar/', navbar, name='navbar'),
]
views
from django.shortcuts import render
def home(request):
return render(request, "home.html")
def navbar(request):
return render(request, "users/navbar.html")
home.html
Log In
navbar.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<h2>This is a navbar template</h2>
</body>
</html>

TemplateDoesNotExist at /test/ error popped up while running application

I am using Django 3.0.8 My view function is as follows:
from django.shortcuts import render import datetime
# Create your views here.
def date_time_view(request):
date=datetime.datetime.now()
h=int(date.strftime('%H'))
if h<12:
msg='Hello Guest!!! Very good Morning!!!'
elif h<16:
msg='Hello Guest!!! Very good Afternoon !!!'
elif h<21:
msg='Hello Guest!!! Very good Evening!!!'
else:
msg='HELLO GUEST!! very good Night!!!'
my_dict = {'date':date,'msg':msg}
return render(request, 'testapp/results.html', my_dict)
and my template is as follows:
<!DOCTYPE html> {%load staticfiles%}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>hello</title>
</head>
<body>
<h1>{{msg}}</h1>
<h2>{{date}}</h2>
<img src="{%static " images/images.jpg" %}">
</body>
</html>
Check your configuration in your project settings file.
Templates can reside in each app separately, but also in a templates folder in APPS_DIR (folder with all Django apps).
Here is official docs for Django 3 templates:
https://docs.djangoproject.com/en/3.0/topics/templates/
Check your template's location. It should be yourproject/yourapp/templates/testapp.

image is not correctly displayed

Hello I'm learning flask and I want to insert an image. But the image is not correctly displayed: there is just an icon in the navigator.
I've tried to change the image extension from .png to .jpg but it doesn't change anything. I also tried to change navigator but it stills the same.
The python code:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/<page_name>/')
def render_static(page_name):
return render_template(f'{page_name}.html')
if __name__ == "__main__":
app.run()
The html code:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<img src="{{url_for('static', filename = 'image/Android_robot.png')}}" alt = "example" />
</body>
</html>
The image should be in static folder. Here is an example of how to use static image in Flask template.
Folder structure:
├── app.py
├── static
│   └── image
│   └── bitcoin.jpg
└── templates
   └── image_example.html
app.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/demo/<page_name>/')
def render_static(page_name):
return render_template('{page_name}.html'.format(page_name=page_name))
if __name__ == "__main__":
app.run(debug=True)
Template image_example.html:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<h2>Bitcoin image should be displayed underneath</h2>
<img height="500px" src="{{url_for('static', filename='image/bitcoin.jpg')}}" alt = "example" />
</body>
</html>
Output of the route http://127.0.0.1:5000/demo/image_example/:

How to host Angular 6 application in Python Django?

I am wanting to host an Angular 6 application in Django, how do I do this?
Integrating Angular 8 and django 2.2
Used Visual Studio for Django 2.2 and Visual Studio Code for Angular 8
I tweaked the above solution and it ultimately worked. devised a simpler solution using some additional references (listed at the end) on top of the above solution.
Assuming:
angular is setup at: example/angular
django is setup at: example/django
Distribute angular files directly to django static folder
This is #1 key, the rest is glue (somewhat ugly) code to stitch the frameworks together as painless as possible.
At the console:
cd example/angular
ng build --prod --output-path ..\django\mysite\mysite\app\static\angular --output-hashing none --watch
Check Angular/CLI for command line switches and their use, the key here that the output of angular compilation goes directly to Django, no need for a middle man.
Maintain independent FE and BE for development and testing
Note: this is optional, you could "ruin" your angular development environment and put all django tags and attributes directly in angular, at the cost of losing FE - BE independence.
The index.html distributed in angular cannot be used "as is" in Django.
Here is such an example call it angular.html:
{% load static %}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>mysite</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="{% static 'angular/favicon.ico' %}">
<link rel="stylesheet" href="{% static 'angular/styles.css' %}">
</head>
<body>
<app-root></app-root>
<script src="{% static 'angular/runtime.js' %}"></script>
<script src="{% static 'angular/polyfills-es5.js' %}"></script>
<script src="{% static 'angular/polyfills.js' %}"></script>
<script src="{% static 'angular/main.js' %}"></script>
</body>
</html>
Note: using only Django native language
Serve it in django like any other html
What else
Two way routing between django and angular
Sharing packages like bootstrap
Strongly recommend django-rest-frame-work as a starting point
BUILDING A WEB APP WITH ANGULAR, DJANGO AND DJANGO REST a more complex example putting it all together, I would keep the above simplified django and angular gluing mechanism.
angular8 django
Assumption: That django site is already running
Things needed to set up Angular 6 locally
Install Node Js.
https://nodejs.org/en/download/
Install Angular cli Globally
npm install -g #angular/cli
Navigate to angular on the repo
dir\angular
Install the npm's [libraries]
npm install
Serve the site
npm serve [-o]
Navigate to the hosted site
http://localhost:4200/
Angular Libraries needed to support Django
npm install #angular-devkit/custom-webpack --save
npm install #angular-builders/custom-webpack --save
npm install webpack-bundle-tracker --save
Django Libraries needed to support Angular
pip install django-webpack-loader
File Architecture - I put my angular project within the djangodir off root
root > djangodir > angular
root > djangodir > static
root > djangodir > templates
root > djangodir > webpack-stats-angular.json
Set Up Angular for Django
1) Alter angular.json to include custom webpack config and change build type to builder
"architect": {
"build": {
"builder": "#angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./extra-webpack.config.js"
},
"outputPath": "../static/angular",
2) extra-webpack.config.js code
const BundleTracker = require('webpack-bundle-tracker');
module.exports = {
plugins:[
new BundleTracker({filename: '../webpack-stats-angular.json'})
],
output: {
path: require('path').resolve('../static/angular'),
filename: "[name]-[hash].js"
}
};
Set Up Django for Angular
1) settings.py - added webpack_loader to installed_apps
INSTALLED_APPS = [
'webpack_loader'
]
2) settings.py - added webpack_loader
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'angular/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats-angular.json'),
}
}
3) requirements.txt - We have a script that pulls from a text file to include dependencies - to this we add
django-webpack-loader==0.6.0
4) urls.py - set up the init routing to the hello world angular app
from . import views as djangodir_views
urlpatterns = [
# path('', include(router.urls)),
path('', djangodir_views.serve_angular, name='serve_angular')
]
5) views.py - include url path
def serve_angular(request):
return render(request, 'angular.html')
Angular.html Page:
{% load render_bundle from webpack_loader %}
<!doctype html>
<html lang="en">
<head>
<base href="/">
<title>Angular/TypeScript Hello World Project</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="Angular Hello World Starter">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<!-- <link href="assets/styles/styles.css" rel="stylesheet" /> -->
</head>
<body>
<header class="navbar navbar-inner navbar-fixed-top">
<nav class="container">
<div class="navbar-header">
<span class="app-title"></span>
</div>
</nav>
</header>
<main class="container">
<app-root>
Loading...
</app-root>
<br /><br />
</main>
<footer>
<div class="navbar navbar-fixed-bottom">
<div class="navbar-inner footer">
<div class="container">
<footer>
</footer>
</div>
</div>
</div>
</footer>
{% render_bundle 'runtime' %}
{% render_bundle 'polyfills' %}
{% render_bundle 'styles' %}
{% render_bundle 'vendor' %}
{% render_bundle 'main' %}
</html>
References:
Angular 6|5 Tutorial: Integrating Angular with Django
Customizing Angular CLI 6 build — an alternative to ng eject
Evolving your Django frontend
Angular Hello World Example used
Routing:
In order for angular routing to work, you must
1) app-routing.module.ts - Add the routing to angular
const routes: Routes = [
{ path: '', component: TestComponent, data: { title: 'Home' }},
{ path: 'test', component: Test2Component, data: { title: 'Test' }}
];
2) urls.py - Add the routing to Django - just point it to the same view
urlpatterns = [
path('', djangodir_views.serve_angular, name='serve_angular'),
path('test', djangodir_views.serve_angular, name='serve_angular')
]

How to serve Angular2 using Django builtin webserver

how to serve Angular2 app using Django builtin webserver?
I think I'm having some problems with the template and static paths from django.
My django project structure looks like following:
DjangoDir/
manage.py
project/
settings.py
urls.py
app1/
app2/
static/
app2/
something.js
something.css
templates/
app2/
index.html
urls.py
views.py
I have an angular2 app with following index:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular2</title>
<base href="/">
<link href="something.css" rel="stylesheet"/>
</head>
<body>
<app-root></app-root><script type="text/javascript" src="something.js"></script>
</body>
</html>
I get HTTP Status 404 (Not Found) code for the something.js and something.css file. Any ideas?
Here is my views.py in app2.
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'app2/index.html')
UPDATE
Working solution, but still looking for alternatives.
Adding to all internal links in the angular2 app:
"/static/app2/"
<!--e.g.:-->
<script type="text/javascript" src="/static/app2/something.js"></script>
or
<!--{% load static %}-->
<script type="text/javascript" src="{% static 'app2/something.js' %}"></script>"
How to avoid changing every link in template and static files just to make angular2 app work with django?
I think that the better way to deal with Django and Angular 2+ is to build an API. You may create an RESTful API with Django REST Framework or Tastypie. Then your Angular2 app would consume that API to create the user-facing experience. You can check django-rest-angular2-example.
However, you want to manage static files, you can read Managing static files