I have scenario where I want to use sockets to wrap my API calls and not available to hit directly the api in browser and get data.
index.html :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Report</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.6.2/css/buttons.dataTables.min.css"/>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"></script>
</head>
<body style="background-color:mintcream;">
<div ><span style="font-family: sans-serif;font-size: x-large;al:center;">reportyu</span> <br> <br>
<table id="example" class="table table-striped table-bordered" style="width:100%;">
<thead>
<tr>
<th>Lame</th>
<th>IAr</th>
<th>Hee</th>
<th>ED</th>
<th>SPs</th>
<th>Ts</th>
<th>SD</th>
<th>Rs</th>
<th>Ld</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Lame</th>
<th>IAr</th>
<th>Hee</th>
<th>ED</th>
<th>SPs</th>
<th>Ts</th>
<th>SD</th>
<th>Rs</th>
<th>Ld</th>
</tr>
</tfoot>
</table>
<script>
function setupData() {
$(document).ready(function () {
$('#example').DataTable({
responsive: true,
"ajax": {
"url": "/index_get_data",
"dataType": "json",
"dataSrc": "data",
"contentType":"application/json"
},
"columns": [
{"data": "L_name"},
{"data": "Ia_r"},
{"data": "He_e"},
{"data": "e_d",
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<a href='//abc.app.com/"+oData.e_d+"'>"+oData.e_d+"</a>");
}
},
{"data": "s_ps"},
{"data": "t_s"},
{"data": "s_d",
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<a href='//app2.com/"+oData.s_d+"'>"+oData.s_d+"</a>");
}
},
{"data": "R_n",
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<a href='//sshse.com/"+oData.R_n+"'>"+oData.R_n+"</a>");
}
},
{"data": "l_d"}
],
dom: 'Bfrtip',
buttons: [
{
extend: 'pdfHtml5',
orientation: 'landscape',
pageSize: 'LEGAL'
},
'copyHtml5',
'excelHtml5'
]
});
});
}
$( window ).on( "load", setupData );
</script>
</body>
</html>
here is my app.py :
from flask import Flask, render_template, jsonify
import json
app = Flask(__name__)
#app.route('/index')
#app.route('/')
def index():
return render_template('index.html')
#app.route('/index_get_data')
def stuff():
# Assume data comes from somewhere else
with open('crtp.json') as test_file:
data = json.load(test_file)
return jsonify(data)
if __name__ == '__main__':
app.run()
This works as expected but when I hit the url localhost:5000 in browser I am also able to see the API call in network tab of the browser and then if I hit the endpoint localhost:5000/index_get_data
I am able to use the API openly.
I have explored options of sending token based auth in headers and basic auth but still the response can be derived and the API is still open for use which I want to restrict , I came across flask-sockets which seems to help here but not sure how can I implement this here.
Any help regarding this or any other approach to achieve this would be great.
It isn't clear what you really are trying to do, and why you don't want 'browsers' to be able to see your endpoints. Flask (and browsers) use HTTP and HTTPS to communicate. There are huge amounts of information, packages, etc about how all that works - and if you are interested in any sort of interoperability - you should stick to well-established protocols. You might be asking how to SECURE your endpoints such that only clients that have appropriate credentials can access your site. That is what packages such as Flask-Security-Too, Flask-Dance, Flask-Login all provide. Flask itself doesn't provide any endpoint protection
Related
I'm trying to configure the display of graphs in Django using highcharts and I encounter this error:
AttributeError: 'WSGIRequest' object has no attribute 'is_ajax'
Code:
views.py
import random
from django.shortcuts import render
from highcharts.views import HighChartsBarView
class BarView(HighChartsBarView):
title = 'Example Bar Chart'
subtitle = 'my subtitle'
categories = ['Orange', 'Bananas', 'Apples']
chart_type = ''
chart = {'zoomType': 'xy'}
tooltip = {'shared': 'true'}
legend = {'layout': 'horizontal', 'align': 'left',
'floating': 'true', 'verticalAlign': 'top',
'y': -10, 'borderColor': '#e3e3e3'}
#property
def series(self):
result = []
for name in ('Joe', 'Jack', 'William', 'Averell'):
data = []
for x in range(len(self.categories)):
data.append(random.randint(0, 10))
result.append({'name': name, "data": data})
return result
index.html
{% % load staticfiles %}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="{% static 'js/highcharts/highcharts.js' %}"></script>
<script type="text/javascript">
$(function () {
$.getJSON("{% url 'bar' %}", function(data) {
$('#container').highcharts(data);
});
});
</script>
</head>
<body>
<div id="container" style="height: 300px"></div>
</body>
</html>
I have no idea how to fix it
Django-braces does not support officially django4+ : https://pypi.org/project/django-braces/
Ths issue has already been fixed in the github, but not yet released.
https://github.com/brack3t/django-braces/issues/288
You can install the github version with pip :
pip install git+https://github.com/brack3t/django-braces.git
I hope there is just this compatibility problem with django 4+ and it will be work
I am new to Azure bot - I have tried to create sample Q&A chat bot. I have embed Chatbot to Sharepoint. Can someone help me how to update the default "Chat" name.
Also, I would like to see in sharepoint how can I implement functionality, so I can expand and collapse the chat window.
For this to happen usually you have to override css and JS functionality. You can find the CSS and JS file here
https://cdn.botframework.com/botframework-webchat/latest/botchat.css
https://cdn.botframework.com/botframework-webchat/latest/webchat.js
You should create your own HTML file where you can host IFRAME and these two files. Sample index.html below
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Using Web Chat v3</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!--
If you want to continue to use the deprecated Web Chat v3, you can use our bundle "botchat.js" or "botchat-es5.js".
Please note that v3 does not have similar customizability and style options as in v4.
-->
<link rel="stylesheet" href="https://cdn.botframework.com/botframework-webchat/latest/botchat.css" />
<script src="https://cdn.botframework.com/botframework-webchat/latest/botchat.js"></script>
<style>
html,
body {
height: 100%;
}
body {
margin: 0;
}
#webchat {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
(async function() {
// In this demo, we are using Direct Line token from MockBot.
// Your client code must provide either a secret or a token to talk to your bot.
// Tokens are more secure. To learn about the differences between secrets and tokens
// and to understand the risks associated with using secrets, visit https://learn.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication?view=azure-bot-service-4.0
const res = await fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { method: 'POST' });
const { token } = await res.json();
BotChat.App(
{
directLine: { token },
user: { id: 'userid' },
bot: { id: 'botid' },
resize: 'detect'
},
document.getElementById('webchat')
);
})().catch(err => console.error(err));
</script>
</body>
</html>
Reference : https://github.com/microsoft/BotFramework-WebChat/blob/master/samples/webchat-v3/
NOTE: You have to make necessary changes in JS and CSS by inspecting the browser chat window
I am following https://help.twitter.com/en/using-twitter/embed-twitter-feed for embedding timeline in the angular page. Only button renders but not the actual timeline.
The index.html looks like:
<body style="margin:0">
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
<app-root></app-root>
</body>
app.component.html looks like below:
<a class="twitter-timeline"
href="https://twitter.com/TwitterDev/lists/national-parks?ref_src=twsrc%5Etfw">
A Twitter List by TwitterDev
</a>
Also tried things like app.component.ts:
ngOnInit(){
if ((<any>window).twttr.ready())
(<any>window).twttr.widgets.load();
}
But no luck
you need to load widgets.js script after twitter-timeline element is been render so if you place the script in index.html it is will load and the element hasn't render yet.
๐ the best way around it is to create a script tag dynamically after the element is rendered.
twitter component
export class TwitterComponent {
#Input() user:string;
constructor(private renderer2: Renderer2,private el: ElementRef) {}
ngAfterViewInit() {
let scriptEl = document.createElement('script');
scriptEl.src = "https://platform.twitter.com/widgets.js"
this.renderer2.appendChild(this.el.nativeElement, scriptEl);
}
}
template
<a class="twitter-timeline" href="https://twitter.com/{{user}}">Tweets by {{user}}</a>
app componenet template
<app-twitter [user]="name"></app-twitter>
angular twitter widgets โกโก
ngAfterViewInit() a lifecycle hook that is called after Angular has fully initialized a component's view.
Updated ๐ฅ๐ฅ
a simple soulution mention in this answer before by user named Bernardo Baumblatt
put the script link in the index.html
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8">
</script>
load the twitter widgets when ngAfterViewInit method call
ngAfterViewInit() {
// #ts-ignore
twttr.widgets.load();
}
in any case the script has not loaded yet you will got an error like ๐ twttr is not defined ๐ so download the widgets.js script and include it to your project by using import
main.ts
import './app/widgets.js'
demo ๐ฅ๐ฅ
I had a requirement of dynamically rendering timelines based on different twitter timelines.
I found a workaround by creating a variable in the constructor that stores the href based on the twitter username .
So for example if your link is "https://twitter.com/TwitterDev/lists/national-parks?ref_src=twsrc%5Etfw"
, you just put this in the constructor in a previously defined global variable , say "embedLink"
such as in your ts component:
#Component({
selector: 'app-tree-dashboard',
templateUrl: './tree-dashboard.component.html',
styleUrls: ['./tree-dashboard.component.css']
})
export class TreeDashboardComponent implements OnInit,AfterViewInit {
embedLink='';
constructor(private matIconRegistry: MatIconRegistry,
) {
this.embedLink= "https://twitter.com/TwitterDev/lists/national-parksref_src=twsrc%5Etfw"
}};
and then in your HTML :
<a class="twitter-timeline" href={{embedLink}}></a>
And lastly you only need to add the script in index.html which you have done already.
So you're good to go!
Below is my code. I'm creating blank website so I think it's should not be a problem. What I think is maybe the order of the script in index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Twitter</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
<app-root></app-root>
</body>
<script
async
src="https://platform.twitter.com/widgets.js"
charset="utf-8"
></script>
</html>
In my app.component.html
<a class="twitter-timeline"
href="https://twitter.com/TwitterDev/lists/national-parks?ref_src=twsrc%5Etfw">
A Twitter List by TwitterDev
</a>
You can view my code here
So, I am getting the below error,
inspected via google chrome
What I am trying to achieve is to explore the Fetch Api by retrieving some data via userApi.js file which pulls it from a srcServer.js (I have hardcoded some data here). I am using webpack bundle and index is the entry point of my project. I have created index.html to bind the data via innerhtml.
Earlier I was using import 'isomorphic-fetch' in my userApi.js file but that too didn't help and hence I found some suggestions on google to use isomorphic-fetch, node-fetch etc. nothing of that sort worked.
I have added most of the artifacts below can you please guide me what is that I am missing here.
Project Structure
userApi.js
import 'isomorphic-fetch'
import 'es6-promise'
export function getUsers () {
return get('users')
}
function get (url) {
return fetch(url).then(onSuccess, onError) //eslint-disable-line
}
function onSuccess (response) {
return response.json()
}
function onError (error) {
console.log(error)
}
index.js
/* eslint-disable */ // --> OFF
import './index.css'
import {getUsers} from './api/userApi'
// Populate table of users via API call.
getUsers().then(result => {
let usersBody = ''
result.forEach(element => {
usersBody+= `<tr>
<td><a href='#' data-id='${user.id}' class='deleteUser'>Delete</a></td>
<td>${user.id}</td>
<td>${user.firstName}</td>
<td>${user.lastName}</td>
</tr>` //eslint-disable-line
})
global.document.getElementById('users').innerHTML = usersBody
})
index.html
<!DOCTYPE <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Users</h1>
<table>
<thead>
<th> </th>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</thead>
<tbody id="users">
</tbody>
</table>
<script src="bundle.js"></script>
</body>
</html>
srcServer.js
// sample api call data
app.get('/users', function (req, res) {
// Hard coded for simplicity
res.json([
{ 'id': 1, 'firstName': 'P', 'lastName': 'K' },
{ 'id': 2, 'firstName': 'M', 'lastName': 'K' },
{ 'id': 3, 'firstName': 'S', 'lastName': 'K' }
])
})
The error is giving you the exact reason, i.e. user is not defined. Have you tried to print console.log(element); in your forEach loop? You will see what you need to change.
You are accessing the user information incorrectly. In your forEach loop, each value is represented as element not user
result.forEach(element => {
usersBody+= `<tr>
<td><a href='#' data-id='${element.id}' class='deleteUser'>Delete</a></td>
<td>${element.id}</td>
<td>${element.firstName}</td>
<td>${element.lastName}</td>
</tr>` //eslint-disable-line
})
I created a web application where it needs to popup images and videos from Fancy boxes called rippolls. Here my "Rippolls" are load in popup boxes and users can vote for those rippolls.
My question is, in one page I listed all rippolls and when I click on a rippoll with an image or video it is loaded withour fancy box and fancy box css.
I have referenced
<script src="../../Content/Scripts/jquery.fancybox-1.3.4.pack.js" type="text/javascript"></script>
<link href="../../Content/Styles/jquery.fancybox-1.3.4.css" rel="stylesheet" type="text/css" />
in a _layout.cshtml where is referenced to the _RippollList.chtml page.
Code in the _RippollList.chtml is :
$("a.btnVotePop#(poll.Id)").fancybox({
'onComplete' : function() {
alert('hello');
try {
FB.XFBML.parse();
twttr.widgets.load();
history.pushState({}, "#poll.Name.Trim()", "/polls/#poll.Id");
document.getElementsByTagName("title")[0].innerHTML = "#poll.Name.Trim()";
//history.replaceState({}, "title", "#poll.Name.Trim()");
//$("#rippoll_image_path").attr("content", $("#polltitle").val());
}
catch (ex) {
alert('Error parsing response.');
}
},
'onClosed' : function(){
alert("closed");
try {
history.pushState({}, "Rippoll", "/home/mypage");
document.getElementsByTagName("title")[0].innerHTML = "My Page";
$('#divDetailCont').css('display', 'none');
}
catch (ex) {
}
},
ajax : {
type : "GET"
},
'width': '560px'
});
Html :
<div id="videoDeftImgContainer" class="videoDefultImg">
<a class="btnVotePop#(poll.Id)" href="RippollCardPopup/#(poll.Id)">
<img class="inImgSize" src="#poll.ImagePath" />
</a>
<div id="plyBtnClk" class="playBtn" onclick="">
<a class="btnVotePop#(poll.Id)" href="RippollCardPopup/#(poll.Id)">
<img src="../../Content/images/newImages/hoverPlay.png" />
</a></div></div>
script references:
<script src="../../Content/Scripts/jquery.fancybox-1.3.4.pack.js" type="text/javascript"></script>
<link href="../../Content/Styles/jquery.fancybox-1.3.4.css" rel="stylesheet" type="text/css" />
but still I m getting a page without fancybox and its styles.
I am in a doubt of because I am putting some text values to rippoll( ex: rippoll name, rippoll question etc..) and it may having some special characters(#%$#{}) also, and is it the reason for not open rippolls in the fancy box.
Help me out for this. please post if any code segments where you successed.