Jinja Flask JS and CSS not loading. static files in static - javascript

I've read multiple posts that static files have to be in the /static/ folder and routed to with url_to in the html template. But it's not working. The entire site renders and loads with localhost, but externally viewed it only loads text, no css or js.
Console says 404: http://exmaple.com/static/scripts/my_app.js
Same applies for any images and css.
/home/me/my_app/web_dynamic/my_app.py
from flask import Flask, render_template, url_for
from models import storage
import uuid
app = Flask(__name__)
app.url_map.strict_slashes = False
port = 5000
host = '0.0.0.0'
#app.route('/', strict_slashes=False)
#app.route('/my_app/', strict_slashes=False)
def filters(the_id=None):
state_objs = storage.all('State').values()
states = dict([state.name, state] for state in state_objs)
places = storage.all('Place').values()
cache_id = uuid.uuid4()
return render_template('my_app.html',
states=states,
places=places,
cache_id=cache_id)
if __name__ == "__main__":
app.run(host=host, port=port)
/home/me/my_app/web_dynamic/temaplates/my_app.html
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="{{ url_for('static', filename='scripts/myscript.js') }}"></script>
</head>
<body>
<! --- HTML and JINJA HERE -->
</body>
</html>

Related

How can I add gsap cdn to flask?

So far I have tried adding the cdn like this which does not work:
#app.route('/')
def home():
cdn = 'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.1/gsap.min.js"'
return render_template('index.html', cdn = cdn)
Here what I want to do is write the js code in html using gsap cdn, however it's not working at all.
index.html:
<head>
<link src="{{ cdn }}" />
rest of the code..
</head>
<body>
<script>
import { gsap, interpolate } from "gsap";
import {ScrollTrigger} from 'gsap/ScrollTrigger';
rest of the code..
</script>
</body>

How can I send captured video stream frames from html to flask server?

I have 3 main code(camera.py, main.py, xx.html) run perfectly in my local server. But I when uploaded them to heroku, application is not working since cv2.VideoCapture isn't triggering webcam on client side.
Main.py:
from flask import Flask, render_template,Response,request,jsonify
from camera import VideoCamera
from flask import redirect,url_for
import os
from PIL import Image
from mains.utils import pipeline_model
from wtforms import Form, BooleanField, StringField, PasswordField, validators
from predictors import RegressionPredictor, CNNPredictor
import numpy as np
UPLOAD_FOLDER ='static/upload'
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
def gen(camera):
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
#app.route('/video_feed')
def video_feed():
return Response(gen(VideoCamera()),
mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(debug=True)
camera.py:
import cv2
face_cascade=cv2.CascadeClassifier("haarcascade_frontalface_alt2.xml")
ds_factor=0.6
class VideoCamera(object):
def __init__(self):
self.video = cv2.VideoCapture(0)
def __del__(self):
self.video.release()
def get_frame(self):
ret,frame = self.video.read()
frame = cv2.resize(frame,None,fx=ds_factor,fy=ds_factor,interpolation=cv2.INTER_AREA)
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
face_rects = face_cascade.detectMultiScale(gray,1.3,5)
for (x,y,w,h) in face_rects:
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
break
ret,jpeg = cv2.imencode('.jpg',frame)
return jpeg.tobytes()
.html code (only related part)
<img id="bg" src="{{url_for('video_feed')}}" alt="">
As I mentioned above code opens my webcam on my browser and detects my face.
I searched and found some javascript code to reach web cam on the client side. Code is like below;
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebcamJS Test Page</title>
<body>
<h1>WebcamJS Test Page</h1>
<h3>Demonstrates simple 320x240 capture & display</h3>
<div id="my_camera"></div>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="static/webcam.min.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
</script>
</body>
</html>
This code works perfectly but I can not figured out how can I send data frames from "Webcam.attach('#my_camera') to flask server to process it using OpenCV? I searched a lot but couldn't find solution maybe its because I am newbie on javascript.
Thanks in advance for your support!
SocketIO was the answer to make connection between server and javascript code.
Please check this repo for more information.
Please check this one to get OpenCV integrated version of above code

how to get React file recognized within Flask project

I'm currently trying to put together a little Flask + React project. I have had some difficulty getting the js file (which contains the react code) to run at all in the project.
This is my project structure, standard for flask:
The route is defined in the routes.py file in the project root
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route("/qubits")
def qubits():
return render_template('qubits.html')
# http://localhost:5000/qubits
if __name__ == "__main__":
app.run(debug=True)
I have my simple html file, which is linking properly to my css (im able to pull in css elements fine).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>nstem</title>
<link rel= "stylesheet" href= "{{ url_for('static',filename='css/nstem.css') }}">
</head>
<body>
<div class="indexBox1"></div>
<h1>: )</h1>
<script type="text/javascript"
src="{{ url_for('static', filename='js/index.js') }}"></script>
</div>
</body>
</html>
However, nothing is being returned on the webpage from these two js files:
*index.js*
import React from 'react';
import ReactDOM from 'react-dom';
import './nstem.css';
import Qubit from './qubits';
ReactDOM.render(
<Qubit />,
document.getElementById('root')
);
* function file *
import React from 'react';
import ReactDOM from 'react';
function Qubit() {
const section = 'lists';
return (
<div>Allah'u'abha</div>
);
}
export default Qubit;
Im pretty stumped; ive played with this so much today and cant figure out where the gap is. Please help, and thanks so much.

How to output $.get() method JQuery with Flask

I could not output the data created in Flask to JQuery in a Html page.
I am testing $.get() method in JQuery with Flask. The task is to return a String to a Html page and display it as paragraph. But the result cannot be displayed. Can someone shed a light on this issue. Thanks!
Here is the code in Flask
from flask import request, jsonify, Flask
app = Flask(__name__)
#app.route('/', methods=["GET"])
#app.route('/hello', methods=["GET"])
def hello():
return jsonify('<h1>Hello Flask !!!</h1>')
Here is the html code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Events </title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function()
{
$("#btnGet").click(function()
{
//$.get('https://httpbin.org/get',
$.get('http://localhost:5000/hello',
function(data)
{
$("#getInfo").text(data)
});
});
});
</script>
</head>
<body>
<button id="btnGet">Click to Get Info </button>
<p id="getInfo"></p>
</body>
</html>
As new to web programming, after hours trial and error, finally found out that I am not placing the html under static folder and run it in Eclipse Environment. After open it up in http://localhost:5000/static/test.html then it works as expected.

Tornado rendered index.html body is empty

I am strating out with Tornado and I am trying to render an index.html template with a static js script on startup.
Here is my main.py:
import tornado.ioloop
import tornado.web
import tornado.websocket
import signal
import logging
from tornado.options import options
import Settings
is_closing = False
def signal_handler(signum, frame):
global is_closing
logging.info('exiting...')
is_closing = True
def try_exit():
global is_closing
if is_closing:
# clean up here
tornado.ioloop.IOLoop.instance().stop()
logging.info('exit success')
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html", title = "Home")
class Application(tornado.web.Application):
def __init__(self):
settings = {
"template_path": Settings.TEMPLATE_PATH,
"static_path": Settings.STATIC_PATH,
}
handlers = [
(r"/", MainHandler),
#(r"/index", tornado.web.StaticFileHandler, dict(path=settings["template_path"]+"/index.html"))
]
tornado.web.Application.__init__(self, handlers, **settings)
if __name__ == "__main__":
application = Application()
tornado.options.parse_command_line()
signal.signal(signal.SIGINT, signal_handler)
application.listen(8888)
tornado.ioloop.PeriodicCallback(try_exit, 100).start()
tornado.ioloop.IOLoop.instance().start()
Here is my index.html:
<html>
<head>
<title>{{ title }}</title>
<script src="{{ static_url("js/main.js") }}" type="javascript"/>
</head>
<body>
<h1>This is currently touching your sockets</h1>
{{ title }}
</body>
</html>
When I request '/' I get a blank page. However the title is set properly and the js is embeded properly. Basically whole head is present, but whole body is empty.
Even more, the html reaches client properly (I can see that in chrome networking dev tools), in the html sent by server the body is present, but somehow not rendered afterwards.
What's happening?

Categories

Resources