Tornado rendered index.html body is empty - javascript

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?

Related

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 can I get a User input and add it in a url and open the url in a new tab?

I know nothing about it.
I need to make a simple website.
I will take an input from user.
Suppose the input is 'LOL'
Then I need to open a new tab with this url - "https://www.help.me/LOL"
#Help me Please
You can do it by using django forms
In your project directory in views.py file you can use this code
from django import forms
from django.http import HttpResponseRedirect
class inputform(forms.Form):
inputfield = forms.CharField(label="Input")
def index(request):
if request.method == "POST":
x = inputform(request.POST)
if x.is_valid():
y = x.cleaned_data["inputfield"]
return
HttpResponseRedirect(f"https://www.help.me/{y}")
return render(request, "index.html", { "form":
inputform() }
In HTML, you can write the following code to represent the Input Field in HTML page
in index.html;
<!DOCTYPE html>
<html lang="en">
<head>
<title> xyz </title>
</head>
<body>
<form method="POST">
{% csrf_token %}
{{form}}
<input type="submit">
</form>
</body>
</html>
By this you will get your desired results

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.

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

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>

Django doesn't seem to be recognizing jquery - what now>

I'm in desperate need of help. I have followed many tutorials, as well as scrutinized this, this, this, and this article. I was getting error messages when following the Django documentation for static servers mentioned in the middle two articles, but I seem to be doing all the right things discussed in the two regarding settings.py, placing jquery.js in the correct directory and referencing the correct source in the actual html file.
My media directory seems to be being referenced - the css file in there is working splendidly, and if I go to http://127.0.0.1:8000/media/jquery.js, the jquery file is displayed.
Still, none of my functions that I've built after following multiple tutorials work for me on my django project. I've been banging my head against the wall for days - please help if you can.
Django App Project File:
__init__.py
data.db
javascript_app/
manage.py
media/
settings.py
templates/
urls.py
views.py
Javascript App Directory:
__init__.py
admin.py
models.py
tests.py
urls.py
views.py
Media Directory:
jquery.js
style_js.css
Templates Directory:
javascript_app/
base.html
note_list.html
In my main settings file:
import os.path
ROOT_PATH = os.path.dirname(__file__)
...
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), "media")
MEDIA_URL = 'http://127.0.0.1:8000/media/'
ADMIN_MEDIA_PREFIX = '/media/admin/'
In my main urls file:
from django.conf.urls.defaults import *
from django.views.static import *
from django.conf import settings
...
urlpatterns = patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT }),
Desperately, I also put a media reference in my javascript_app 's urls.py (with the above-referenced import commands as well):
urlpatterns = patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT }),
In templates/javascript/base.html:
<head>
<title>{% block title %}Notes Application{% endblock %}</title>
<link rel="stylesheet" href="/media/style_js.css">
<script type="text/javascript" src="/jennystanchak/media/jquery.js"></script>
</head>
And finally in templates/javascript/note_list.html:
{% extends "javascript/base.html" %}
{% block content %}
...
<script>
// my script here
</script>
{% endblock %}
What in the configuration am I missing??
Thank you SO MUCH in advance for your help :)
-- An aspiring female programmer
<script type="text/javascript" src="/jennystanchak/media/jquery.js"></script>
Shouldn't the path be src="/media/jquery.js" without /jennystanchak ?

Categories

Resources