There is a python script for face recognition that i want to modify and run it in my laravel application to give access to the users to a page using face recognition. But i have no idea how to do that.
Here is the original html ( not the one of my application) :
you take a snapshot and compare the image with images you have in a folder
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
<title>Login</title>
</head>
<body onload="init()">
<nav class="navbar text-white navbar-dark bg-dark">
<a href="#" class="navbar-brand">
Login
</a>
</nav>
<p>
</p>
<div class="container text-center bordered" style="width:280px">
<form action="login.py" method="post" enctype="multipart/form-data">
<video onclick="snapshot(this);" width=250 height=250 id="video" controls autoplay></video>
<br>
<input type="email" placeholder="Email" name="email" class="form-control form-control-sm text-left">
<br>
<input type="text" accept="image/png" hidden name="current_image" id="current_image">
<button onclick="login()" class="btn-dark" value="login">Login </button>
<br>
<br>
</form>
</div>
<canvas id="myCanvas" width="400" height="350" hidden></canvas>
</body>
<script>
//--------------------
// GET USER MEDIA CODE
//--------------------
navigator.mediaDevices.getUserMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
var video;
var webcamStream;
if (navigator.getUserMedia) {
navigator.getUserMedia (
// constraints
{
video: true,
audio: false
},
// successCallback
function(localMediaStream) {
video = document.querySelector('video');
video.srcObject = localMediaStream;
webcamStream = localMediaStream;
},
// errorCallback
function(err) {
console.log("The following error occured: " + err);
}
);
} else {
console.log("getUserMedia not supported");
}
var canvas, ctx;
function init() {
// Get the canvas and obtain a context for
// drawing in it
mcanvas = document.getElementById("myCanvas");
ctx = mcanvas.getContext('2d');
}
function login() {
// Draws current image from the video element into the canvas
ctx.drawImage(video,0,0,mcanvas.width,mcanvas.height);
var dataURL = mcanvas.toDataURL('image/png');
document.getElementById("current_image").value=dataURL;
}
</script>
</html>
and the python :
#!"C:\Users\aya-i\AppData\Local\Programs\Python\Python38\python.exe"
import cgi
from base64 import b64decode
import face_recognition
formData = cgi.FieldStorage()
face_match=0
image=formData.getvalue("current_image")
email=formData.getvalue("email")
data_uri = image
header, encoded = data_uri.split(",", 1)
data = b64decode(encoded)
with open("image.png", "wb") as f:
f.write(data)
got_image = face_recognition.load_image_file("image.png")
existing_image = face_recognition.load_image_file("students/"+email+".jpg")
got_image_facialfeatures = face_recognition.face_encodings(got_image)[0]
existing_image_facialfeatures = face_recognition.face_encodings(existing_image)[0]
results= face_recognition.compare_faces([existing_image_facialfeatures],got_image_facialfeatures)
if(results[0]):
face_match=1
else:
face_match=0
print("Content-Type: text/html")
print()
if(face_match==1):
print("<script>alert('welcome ",email," ')</script>")
else:
print("<script>alert('face not recognized')</script>")
Any external commands such as unix terminal commands, python command and ... should be run with PHP's exec() function. This function runs your commands and has an option to get the output of your command, you have to handle the error and success output yourself.
Related
What is the simplest way to change class name form .black to .white in the example below using python and flask framework? For example: after mouse click on div #area ?
CSS file:
#area {position:absolute;width:100px;height:100px;}
.black {background-color:#000;}
.white {background-color:#fff;}
HTML file:
<!doctype html>
<html>
<head>
<title>Title</title>
<link rel="stylesheet" href="{{ url_for('static',filename='style.css')}}">
</head>
<body>
<div id="area" class="black"></div>
</body>
</html>
This need JavaScript and it has nothing to do with Flask
Example using querySelector()
<div id="area" class="black" onclick="change();"></div>
<script>
area = document.querySelector('#area');
function change(){
area.classList.replace('black', 'white');
}
</script>
or using special variable this
<div id="area" class="black" onclick="change(this);"></div>
<script>
function change(item){
item.classList.replace('black', 'white');
}
</script>
Eventually you could use addEventListener instead of onclick
<div id="area" class="black"></div>
<script>
function change(){
this.classList.replace('black', 'white');
}
area = document.querySelector('#area');
area.addEventListener('click', change);
</script>
or shorter
<div id="area" class="black"></div>
<script>
area = document.querySelector('#area');
area.addEventListener('click', function(){
this.classList.replace('black', 'white');
});
</script>
or even little shorter
<div id="area" class="black"></div>
<script>
document.querySelector('#area').addEventListener('click', function(){
this.classList.replace('black', 'white');
});
</script>
Minimal working code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
<style>
#area1 {width:100px;height:100px;}
#area2 {width:100px;height:100px;}
#area3 {width:100px;height:100px;}
#area4 {width:100px;height:100px;}
.black {background-color:#000;}
.white {background-color:#fff;}
</style>
</head>
<body>
<div id="area1" class="black" onclick="change1();"></div>
<br>
<div id="area2" class="black" onclick="change2(this);"></div>
<br>
<div id="area3" class="black"></div>
<br>
<div id="area4" class="black"></div>
<script>
area1 = document.querySelector('#area1');
function change1(){
area1.classList.replace('black', 'white');
console.log('change1');
}
function change2(item){
item.classList.replace('black', 'white');
console.log('change2');
}
function change3(){
this.classList.replace('black', 'white');
console.log('change3');
}
area3 = document.querySelector('#area3');
area3.addEventListener('click', change3);
area4 = document.querySelector('#area4');
area4.addEventListener('click', function(){
this.classList.replace('black', 'white');
console.log('change4');
});
</script>
</body>
</html>
Using Python you would have to use <a></a> which would send information to server when you click it. And server would use Python to generate HTML with new class and send it back to browser. But it means to reload all page and it needs time.
Minimal working code:
I put black area in <a></a> which ?color=white and when server gets it then it sends back HTML with white area and with ?color=black, etc.
from flask import Flask, request, render_template_string
app = Flask(__name__)
#app.route('/')
def index():
color = request.args.get('color', 'black')
if color == 'black':
other = 'white'
else:
other = 'black'
return render_template_string('''
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
<style>
#area {width:100px;height:100px;}
.black {background-color:#000;}
.white {background-color:#fff;}
</style>
</head>
<body>
<div id="area" class="{{ color }}"></div>
</body>
</html>''', color=color, other=other)
if __name__ == '__main__':
app.run()
It is not popular but you can load JavaScript module Brython to run some Python code in web browser. But you can uses only modules converted to JavaScript
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
<style>
#area {width:100px;height:100px;}
.black {background-color:#000;}
.white {background-color:#fff;}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/brython/3.9.1/brython.min.js"></script>
</head>
<body onload="brython()">
<div id="area" class="black"></div>
<script type="text/python">
from browser import document
def change(ev):
if document['area'].attrs['class'] == 'black':
document['area'].attrs['class'] = 'white'
else:
document['area'].attrs['class'] = 'black'
document["area"].bind("click", change)
</script>
</body>
</html>
There is also transcrypt which can convert some Python code to JavaScript code and run in web browser.
Similar module RapydScript
Thanks, but it must be Python. I have found solution for printing a list, for example:
If I create a list called 'content'=['white','black'] the code below will print: white black and it works fine.
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="{{ url_for('static',filename='style.css')}}">
</head>
<body>
{% for x in content %}
{{x}}
{% endfor %}
</body>
</html>
So according to my question the code below should also work:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="{{ url_for('static',filename='style.css')}}">
</head>
<body>
{% if x==1 %}
<div id="area" class="white"></div>
{% else %}
<div id="area" class="black"></div>
{% endif %}
</body>
</html>
But it doesn't, any ideas?
I'm building a simple image navigator application in Python using Flask. I want to have forward and backward buttons to navigate through all the images in the static folder. So far, I've a single button which displays the image without refreshing the page. How can I navigate through the directory using buttons?
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def hello():
return render_template('upload.html')
#app.route("/getimage")
def get_img():
return "00621.jpg"
if __name__ == '__main__':
app.run()
upload.html
<!DOCTYPE html>
<html lang="en">
<style>
img {
max-width: 100%;
max-height: 100%;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#retrieve').click(function(){
$.ajax({
url: "{{ url_for ('get_img') }}",
type : 'POST',
contentType: 'application/json;charset=UTF-8',
data : {'data':{{}}}
success: function(response) {
$("#myimg").attr('src', 'static/' + response);
},
error: function(xhr) {
//Do Something to handle error
}
});
});
});
</script>
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Image Annotator</h1>
</div>
<button type='button' id ='retrieve'>Submit</button>
<img src="" id="myimg" />
</div>
</div>
</body>
</html>
I have reconstructed some of your code to achieve the answer. Please be aware that I've switched things from Jquery to JS.
New HTML Page:
<!DOCTYPE html>
<html lang="en">
<style>
img {
max-width: 100%;
max-height: 100%;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Image Annotator</h1>
</div>
<button type='button' onclick="oclick()" id='retrieve'>Submit</button>
<button onclick="action(2)" type="button">Backward</button><button onclick="action(1)" type="button">Forward</button>
<image src="" id="myimg"></image>
</div>
</div>
<script>
var imgap = 0
function oclick(){
var getInitialImage = new XMLHttpRequest();
getInitialImage.open("GET", "/getimage");
getInitialImage.onreadystatechange = function (){
if (this.readyState == 4 && this.status == 200){
document.getElementById("myimg").setAttribute("src", "/image/" + this.responseText);
}
}
getInitialImage.send();
}
function action(ac){
if (ac == 1){
imgap += 1
var getnextimagedetails = new XMLHttpRequest();
getnextimagedetails.open("GET", "/getimage?num=" + imgap.toString());
getnextimagedetails.onreadystatechange = function (){
if (this.readyState == 4 && this.status == 200){
document.getElementById("myimg").setAttribute("src", "/image/" + this.responseText);
}
}
getnextimagedetails.send();
}
if (ac == 2){
imgap += -1
var getlastimagedetails = new XMLHttpRequest();
getlastimagedetails.open("GET", "/getimage?num=" + imgap.toString());
getlastimagedetails.onreadystatechange = function (){
if (this.readyState == 4 && this.status == 200){
document.getElementById("myimg").setAttribute("src", "/image/" + this.responseText);
}
}
getlastimagedetails.send();
}
}
</script>
</body>
</html>
New Flask Document:
from flask import Flask, send_from_directory, request
import os
app = Flask(__name__)
#app.route("/")
def hello():
return send_from_directory('', 'upload.html')
#app.route("/image/<path:path>")
def image(path):
print(path)
if (path.endswith(".jpg") or path.endswith(".png") or path.endswith(".bmp") or path.endswith(".jpeg")):
return send_from_directory("", path)
return "", 500
#app.route("/getimage")
def get_img():
print(request.args.get("num"))
if (request.args.get("num") != None):
dirfiles = os.listdir()
presentedstr = []
for string in dirfiles:
if (string.endswith(".jpg") or string.endswith(".svg") or string.endswith(".bmp") or string.endswith(".jpeg") or string.endswith(".png")):
presentedstr.append(string)
presentedstr.index("00621.jpg")
return presentedstr[presentedstr.index("00621.jpg") + int(request.args.get("num"))]
else:
return "00621.jpg"
if __name__ == '__main__':
app.run()
How this implementation works, is the button will send out a request to the server for what the next image or item is, before making another request for the actual next image itself. It will search the same directory.
So what can I do to pass the argument to the function.
import os, random, string
import cherrypy
class StringGenerator(object):
#cherrypy.expose
def index(self):
return """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head
content must come *after* these tags -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="jumbotron">
<p ><h4 class='text-success' style='margin-left:30%;'>This is the twitter
word select </h1></p>
<form class="form-inline" action="generate/" style='margin-left:20%;'
enctype= "multipart/form-data">
<div class="form-group" >
<label for="exampleInputName2">Enter the file name</label>
<input type="file" class="form-control" name="file1" id="file" placeholder=" enter the file ">
</div><div class="form-group" >
<label for="exampleInputName2">Enter the prefrence</label>
<input type="text" class="form-control" name="length" id="exampleInputName2" placeholder=" enter the preference ">
</div>
<button type="submit" class="btn btn-primary">Result</button>
</form>
</div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>"""
#cherrypy.expose
def generate(self, length,file1):
some_string = "harsh"+length
cherrypy.session['mystring'] = some_string
fp = open(file1)
return fb
#cherrypy.expose
def display(self):
return cherrypy.session['mystring']
if __name__ == '__main__':
conf = {
'/': {
'tools.sessions.on': True,
'tools.staticdir.root': os.path.abspath(os.getcwd())
},
'/static': {
'tools.staticdir.on': True,
'tools.staticdir.dir': './public'
}
}
cherrypy.quickstart(StringGenerator(), '/', conf)
Take a look into the file cherrypy files tutorial, but to provide you with a concrete answer, your generate method has to use the file attribute of the file1 parameter.
For example, this method would work:
#cherrypy.expose
def generate(self, length, file1):
some_string = "harsh" + length
cherrypy.session['mystring'] = some_string
file_content = file1.file.read()
return file_content
You can also operate on the file attribute to get more information, it's an instance of a python TemporaryFile.
First, I am fairly new to javascript but I know my way around python. I am trying to learn javascript and I may be out of my league with trying this, but that is how you learn right.
Secondly, Flask and AngularJS play well together with a little help. Special thanks goes to shea256 (https://github.com/shea256/angular-flask)
Now, I am able to get the 'test application' up and running fairly easily.
However, I want to add DevExtreme to this stack and I am having some issues.
Here is what I have:
index.html
<!doctype html>
<html lang="en" ng-app="AngularFlask">
<head>
<meta charset="utf-8">
<title>AngularFlask</title>
<link rel="stylesheet" href="/static/css/bootstrap.css">
<link rel="stylesheet" href="/static/css/main.css">
<link rel="stylesheet" type="text/css" href="http://cdn3.devexpress.com/jslib/16.1.5/css/dx.common.css" />
<link rel="stylesheet" type="text/css" href="http://cdn3.devexpress.com/jslib/16.1.5/css/dx.light.css" />
<!--<script src="/static/lib/jquery/jquery.min.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <!--2.7.0-->
<!--<script src="/static/lib/angular/angular.js"></script>
<script src="/static/lib/angular/angular-resource.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-route.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-sanitize.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/globalize/0.1.1/globalize.min.js"></script>
<!--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
-->
<script type="text/javascript" src="http://cdn3.devexpress.com/jslib/16.1.5/js/dx.web.js"></script>
<script src="/static/js/app.js"></script>
<script src="/static/js/controllers.js"></script>
<script src="/static/js/services.js"></script>
<script src="/static/lib/bootstrap/bootstrap.min.js"></script>
</head>
<body>
<div id="header" class="header navbar navbar-static-top">
<div class="navbar-inner">
<div class="container">
<button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
</button>
<a class="brand" href="/">AngularFlask</a>
<div class="nav-collapse collapse">
<ul class="nav pull-right">
<li class="">
Home
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="container page">
<div id="content" class="container main" ng-view>
</div>
<hr>
<footer id="footer" class="footer">
<div class="footer-left">
About |
Home
</div>
<div class="footer-right">
<span>© 2013 AngularFlask</span>
</div>
</footer>
</div>
</body>
</html>
controllers.js
function IndexController($scope) {
}
function AboutController($scope) {
}
function PostListController($scope, Post) {
var postsQuery = Post.get({}, function(posts) {
$scope.posts = posts.objects;
});
}
function PostDetailController($scope, $routeParams, Post) {
var postQuery = Post.get({ postId: $routeParams.postId }, function(post) {
$scope.post = post;
});
}
app.js
'use strict';
angular.module('AngularFlask', ['angularFlaskServices', 'dx'])
.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'static/partials/landing.html',
controller: IndexController
})
.when('/about', {
templateUrl: 'static/partials/about.html',
controller: AboutController
})
.when('/post', {
templateUrl: 'static/partials/post-list.html',
controller: PostListController
})
.when('/post/:postId', {
templateUrl: '/static/partials/post-detail.html',
controller: PostDetailController
})
/* Create a "/blog" route that takes the user to the same place as "/post" */
.when('/blog', {
templateUrl: 'static/partials/post-list.html',
controller: PostListController
})
.otherwise({
redirectTo: '/'
})
;
$locationProvider.html5Mode(true);
}])
;
With this, when I navigate to localhost:5000, this error is reported
https://docs.angularjs.org/error/$injector/modulerr?p0=AngularFlask&p1=%5B$injector:unpr%5D%20http:%2F%2Ferrors.angularjs.org%2F1.5.7%2F$injector%2Funpr%3Fp0%3D%2524routeProvider%0AO%2F%3C#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:6:412%0Adb%2Fn.$injector%3C#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:43:84%0Ad#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:40:344%0Ae#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:41:78%0Ah%2F%3C.invoke#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:41:163%0Ad#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:39:313%0Ag%2F%3C#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:39:445%0Ar#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:7:353%0Ag#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:39:222%0Adb#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:43:246%0ABc%2Fc#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:20:359%0ABc#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:21:163%0Age#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:19:484%0A#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:315:135%0An.Callbacks%2Fi#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fjquery%2F1.12.4%2Fjquery.min.js:2:27444%0An.Callbacks%2Fj.fireWith#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fjquery%2F1.12.4%2Fjquery.min.js:2:28213%0A.ready#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fjquery%2F1.12.4%2Fjquery.min.js:2:30004%0AK#https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fjquery%2F1.12.4%2Fjquery.min.js:2:30366%0AO%2F%3C()%20angular.min.js:6g%2F%3C()%20angular.min.js:40r()%20angular.min.js:7g()%20angular.min.js:39db()%20angular.min.js:43Bc%2Fc()%20angular.min.js:20Bc()%20angular.min.js:21ge()%20angular.min.js:19%3Canonymous%3E%20angular.min.js:315n.Callbacks%2Fi()%20jquery.min.js:2n.Callbacks%2Fj.fireWith()%20jquery.min.js:2.ready()%20jquery.min.js:2K()%20jquery.min.js:21%20angular.min.js:6:412
It may be worth mentioning that if I use AngularJS 1.0.7 (included with Angular-Flask) the issue is cleared up until I add my html dev tag
<div dx-button="{
text: 'Generate random value'
}"></div>
then these are the errors:
Error: e.$$postDigest is not a function
Error: t.$root is undefined
Error: a.$watch is not a function
Error: c.$watch is not a function
Error: a.$watch is not a function
Error: t.dxTemplateModel is undefined
So this tells me that DevExpress is missing some functions in AngularJS 1.0.7; However, when using AngularJS 1.2.X Angular-Flask breaks. Is there anyway to get these two to play well together?
DevExtreme supports AngularJS 1.2 - 1.4. Your try to use too old version of AngularJS. Scripts in this repo were updated 3 years ago. But you can easily use another angularjs version. Your flask layout can look like below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ title }} - My Flask Application</title>
<link rel="stylesheet" type="text/css" href="/static/content/site.css" />
<link rel="stylesheet" type="text/css" href="http://cdn3.devexpress.com/jslib/16.1.5/css/dx.common.css" />
<link rel="stylesheet" type="text/css" href="http://cdn3.devexpress.com/jslib/16.1.5/css/dx.light.css" />
</head>
<body class="dx-theme-generic-typography" ng-app="myApp">
<div ng-controller="defaultCtrl">
<div dx-button="buttonOptions"></div>
</div>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular-sanitize.js"></script>
<script src="http://cdn3.devexpress.com/jslib/16.1.5/js/dx.all.js"></script>
<script src="/static/scripts/application.js"></script>
</body>
</html>
And the /static/scripts/application.js file:
var myApp = angular.module("myApp", ["dx"]);
myApp.controller("defaultCtrl", function($scope) {
$scope.buttonOptions = {
text: "My button",
onClick: function(){
alert("Hi!");
}
};
});
I am trying to implement the same stack overflow text-area with syntax highlighting in Python and have come this far but i am not able to get it working.
app.py
from flask import Flask, render_template, request
import preview
app = Flask(__name__)
#app.route('/',methods=['GET','POST'])
def index():
if request.method == 'POST':
markdown_content = request.args.get['wdd-input']
post_preview = preview.markdown(markdown_content['data'])
return render_template('test.html', result=post_preview)
if request.method == 'GET':
return render_template('demo.html')
if __name__ == '__main__':
app.run()
preview is something which does syntax highlighting and its based upon Pygments.
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PageDown Demo Page</title>
<link rel="stylesheet" type="text/css" href="/static/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/static/css/highlighting.css">
<link rel="stylesheet" type="text/css" href="/static/css/demo.css" />
<script type="text/javascript" src="/static/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="/static/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/static/js/hycus-textarea.js"></script>
<script type="text/javascript" src="/static/js/Markdown.Editor.js"></script>
<script type="text/javascript">
(function (m) {
m(document).ready(function () {
m('textarea.wmd-input').TextAreaResizer();
});
})(jQuery);
</script>
</head>
<body>
<div class="container">
<div id="pagedwon">
<div id="tabnav">
<ul class="nav nav-tabs" id="markdown_tab" style="padding: 0 10px; margin-bottom: 10px;">
<li class="active">Edit</li>
<li>Preview</li>
</ul>
</div>
<div class="tab-content">
<div class="tab-pane active" id="edit">
<div class="wmd-panel">
<div id="wmd-button-bar"></div>
<textarea class="wmd-input" id="wmd-input" rows="10" name="text-input">
This is the *pagedown* editor.
------------------------------
**Note**: Just plain **Markdown**, except that the input is sanitized: **HTML** is not allowed.
</textarea>
</div>
<script type="text/javascript">
(function () {
var pagedown_editor = new Markdown.Editor();
pagedown_editor.run();
})();
</script>
<script type="text/javascript">
(function (m) {
m("#markdown_tab a").click(function () {
if (m(this).html() == "Preview"){
var markdown_content = m("#wmd-input").val();
if (!markdown_content) {
m("div#markdownpreview").html("Empty Markdown Content.");
} else {
content_to_preview = {
"data": markdown_content
}
m.post("/", content_to_preview)
.success( function(preview_content){
if (preview_content == 'None'){
m("div#markdownpreview").html("No content received.");
} else {
m("div#markdownpreview").html(preview_content);
}
})
.error( function () {
m("div#markdownpreview").html("Sorry, error occurred. Please retry.");
});
}
}
});
})(jQuery);
</script>
</div>
<div class="tab-pane markdown-body" id="markdownpreview">
Loding preview content ...
</div>
</div>
</div>
</div>
</body>
</html>
This is log from the console:
127.0.0.1 - - [26/Jun/2014 20:25:01] "POST / HTTP/1.1" 500 -
How to get it working, please help. I am new to Flask.
First, request.args is for query string parameters, but you are sending over data via POST. You should be using request.form instead.
Second, MultiDict.get is a function, and does not support the __getitem__ protocol (which is the cause of your 500 error).
Third, as #Doobeh points out in the comments, you are sending the data over under the key data, but you are trying to access it via the key "wdd-input" - this will result in a BadRequest error.
Finally, the value extracted from request.form will be a string (which does not support strings as __getitem__ values) - and you don't need it anyway, as you already have the entire string.
A re-worked version of your POST portion:
if request.method == 'POST':
markdown_content = request.form.get('data', 'No content yet ...')
post_preview = preview.markdown(markdown_content)
return render_template('test.html', result=post_preview)