AngularJS & Flask : Passing data to html - angularjs

I am trying to send the data from Flask to AngularJS.
Server
#app.route("/data")
def getDataFromDB():
cur.execute("select * from employee")
rows = cur.fetchall()
columns = [desc[0] for desc in cur.description]
result = []
for row in rows:
row = dict(zip(columns, row))
json_row=json.dumps(row)
result.append(json_row)
json_response=json.dumps(result)
response=Response(json_response,content_type='application/json; charset=utf-8')
response.headers.add('content-length',len(json_response))
response.status_code=200
return response
Client
maincontroller.js
var app=angular.module('myApp',[]);
app.controller("MainController", function($scope,$http){
var done=function(resp){
$scope.lists=resp.data;
};
var fail=function(err){
};
$http.get('http://10.62.XX.XX:8083/data')
.then(done,fail);
});
index.html
<!DOCTYPE html>
<head>
<title>Learning AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"
type="text/javascript"></script>
<script src="app.js" type="text/javascript"></script>
<script src="maincontroller.js" type="text/javascript"></script>
</head>
<body ng-app="myApp">
<div id='content' ng-controller='MainController'>
<div>
<ul>
<li ng-repeat='ele in list'>{{ele}}</li>
</ul>
</div>
</div>
</body>
</html>
Now, when I access the above code using jsbin.com, I can see my api getting called but nothing is visible on the output screen in jsbin. It is blank.
But when I put the same code in eclipse, I see no api call happening. Do I need to do something more to make angularJS work? I just open the index.html with web browser.

If the IP is not your local machine you need to setup CORS on the server. I am not familiar with Flask but it looks like there is a package that handles this. I also found a function that sets up CORS for Flask.
from datetime import timedelta
from flask import Flask, make_response, request, current_app
from functools import update_wrapper
def crossdomain(origin=None, methods=None, headers=None, max_age=21600, attach_to_all=True, automatic_options=True):
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))
if headers is not None and not isinstance(headers, basestring):
headers = ', '.join(x.upper() for x in headers)
if not isinstance(origin, basestring):
origin = ', '.join(origin)
if isinstance(max_age, timedelta):
max_age = max_age.total_seconds()
def get_methods():
if methods is not None:
return methods
options_resp = current_app.make_default_options_response()
return options_resp.headers['allow']
def decorator(f):
def wrapped_function(*args, **kwargs):
if automatic_options and request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, **kwargs))
if not attach_to_all and request.method != 'OPTIONS':
return resp
h = resp.headers
h['Access-Control-Allow-Origin'] = origin
h['Access-Control-Allow-Methods'] = get_methods()
h['Access-Control-Max-Age'] = str(max_age)
if headers is not None:
h['Access-Control-Allow-Headers'] = headers
return resp
f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)
return decorator
#app.route('/')
#crossdomain(origin='*')
def landing():
return jsonify(i_am_a='cross domain resource!')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)

Related

Call Solana web3.js from HTML

I am trying to run web3.js from HTML. Now so far I have been able to call window.solana.connect(); and window.solana.disconnect(); functions. However when I try run below code it doesn't work. I have tested it various options, like removing "web3." from the code but still didn't work. I would apprecaite if someone can guide me on how I can establish the connection.
const connection = new web3.Connection(web3.clusterApiUrl("devnet"));
Majority of my codes below is from the research done on Stackoveflow. Links below:
Solana : Adding Sollet / Phantom Wallet Connect to my website - Steps?
I would like to mint a new token on solana. How can I do this using solana-web3.js?
How can you transfer SOL using the web3.js sdk for Solana?
How to properly transfer Solana SOL using web3js via Phantom
Unfortunately docs on Phantom website don't help either. https://docs.phantom.app/integrating/establishing-a-connection
My existing codes below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome to Decentralized Ecommerce</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/web3/3.0.0-rc.5/web3.min.js" integrity="sha512-jRzb6jM5wynT5UHyMW2+SD+yLsYPEU5uftImpzOcVTdu1J7VsynVmiuFTsitsoL5PJVQi+OtWbrpWq/I+kkF4Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="{{ url_for('static', filename='app.js') }}"></script>
<script src="https://unpkg.com/#solana/web3.js#latest/lib/index.iife.js"></script>
<script src="/static/solana.js"></script>
<script type="text/javascript">
async function transferSOL() {
//Changes are only here, in the beginning
if (window.solana.isConnected === false){
const resp = await window.solana.connect();
}
const pubKey = await window.solana.publicKey;
console.log("Public Key: ", pubKey);
// Establishing connection
const connection = new web3.Connection(web3.clusterApiUrl("devnet"));
alert('hello2');
// I have hardcoded my secondary wallet address here. You can take this address either from user input or your DB or wherever
var recieverWallet = new web3.PublicKey("4iSD5Q6AnyhRHu6Uz4u1KAzXh3TwNwwQshEGhZbEXUTw");
alert('hello3');
// Airdrop some SOL to the sender's wallet, so that it can handle the txn fee
var airdropSignature = await connection.requestAirdrop(
provider.publicKey,
web3.LAMPORTS_PER_SOL,
);
// Confirming that the airdrop went through
await connection.confirmTransaction(airdropSignature);
console.log("Airdropped");
var transaction = new web3.Transaction().add(
web3.SystemProgram.transfer({
fromPubkey: provider.publicKey,
toPubkey: recieverWallet,
lamports: web3.LAMPORTS_PER_SOL //Investing 1 SOL. Remember 1 Lamport = 10^-9 SOL.
}),
);
// Setting the variables for the transaction
transaction.feePayer = await provider.publicKey;
let blockhashObj = await connection.getRecentBlockhash();
transaction.recentBlockhash = await blockhashObj.blockhash;
// Transaction constructor initialized successfully
if(transaction) {
console.log("Txn created successfully");
}
// Request creator to sign the transaction (allow the transaction)
let signed = await provider.signTransaction(transaction);
// The signature is generated
let signature = await connection.sendRawTransaction(signed.serialize());
// Confirm whether the transaction went through or not
await connection.confirmTransaction(signature);
//Signature or the txn hash
console.log("Signature: ", signature);
}
</script>
</head>
After importing the script on the HTML:
<script src="https://unpkg.com/#solana/web3.js#latest/lib/index.iife.js"> </script>
You should be able to call:
const connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl("mainnet-beta"));
Note it is solanaWeb3 not web3
Here is an example with Solana Web3 1.4:
import { Connection, clusterApiUrl } from "#solana/web3.js";
const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
Make sure to have installed the library via, npm install #solana/web3.js.

Media.net ads integration with SPA(angularjs)

How to integrate media.net ads in SPA(angularjs) website. I have copied and posted the given code in my website but it is not working(http://test.website.paperboy.com/).
<script id="mNCC" language="javascript">
medianet_width = "728";
medianet_height = "90";
medianet_crid = "xyz";
medianet_versionId = "xyz";
</script>
<script src="//contextual.media.net/nmedianet.js?cid=xyz"></script>
But it is working for non angular static site(https://test.website.paperboy.com/mobile-view.html).
I cannot speak for angularjs, but Angular 2 and beyond scrubs out script tags. Here is the solution for Angular 8. Note this is for the asynchronous ad code, not the synchronous code posted, but the methodology should be the same in which we are adding a DOM element:
.ts file:
convertToScript() {
var element = this.script.nativeElement;
var script = document.createElement('script');
script.id = 'mNCC';
script.lang = this.language ? this.language : 'javascript';
script.type = this.type ? this.type : 'text/javascript';
script.innerHTML = `
try {
window._mNHandle.queue.push(function (){
window._mNDetails.loadTag(${this.advertisement});
});
}
catch (error) {}`;
script['data-cfasync'] = 'false';
const parent = element.parentElement;
parent.parentElement.replaceChild(script, parent);
}
ngAfterViewInit() {
this.convertToScript();
}
.html file:
<div #script style.display="none">
<ng-content></ng-content>
</div>
Add the component where you want (inject the advertisement size and id here)
<div id="616415456">
<app-media-net-ad [type]="'text/javascript'" [advertisement]="advertisement">
</app-media-net-ad>
</div>
The advertisement variable should be formated as "ad_id,ad_size,ad_id". The header code can be added into the header section of your index.html file.

emails from gmail but response is gmail.readonly

I am trying to get the emails from gmail using https://www.googleapis.com/auth/gmail.readonly/?access_token='fdrt654vfdgfe6545But in response I am getting gmail.readonlyBut the System.HttpResponse[Status=OK, StatusCode=200] is fine. Can any guide me is there anything I am missing out.
This I how I requested got auth but in the response I received access token
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
var AuthStates = {google: null};
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
// Update the app to reflect a signed in user
// Hide the sign-in button now that the user is authorized, for example:
document.getElementById('signinButton').setAttribute('style', 'display: none');
//alert(authResult['code']);
console.log('code state: ' + authResult['code']);
//console.log('authResult : ' + authResult[]);
AuthStates.google = authResult;
console.log('authResult 1 : ' + authResult['status']['method']);
console.log('auth Result : ' + authResult['id_token']);
//{!access_token} = authResult['access_token'];
//{!code} = authResult['code'];
connection(authResult['access_token'], authResult['code']);
} else {
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
}
</script>
<apex:outputPanel >
<span id="signinButton">
<span
class="g-signin"
data-callback="signinCallback"
data-clientid="clientid"
data-cookiepolicy="single_host_origin"
data-scope="https://www.googleapis.com/auth/gmail.readonly"
data-response_type="code"
data-redirect_uri="http://test-on.ap1.visual.force.com/apex/Gmail_inbox">
</span>
</span>
<apex:form >
So as i got my access token from my request I can go directly for getting all information related to the logedin user. As I am getting all the information regarding the user I am trying to get all the emails related to him. Is I am doing right or I am wrong any place. I am very new with api and web service trying to learn. please do help me put out.
You're actually making an HTTP GET call to that URL ( https://www.googleapis.com/auth/gmail.readonly/?access_token= ...)? Isn't that just the auth scope identifier?
Once you have a valid Oauth2 token you can set in the Auth header then you can make HTTP requests to the API. For example, to list messages see:
https://developers.google.com/gmail/api/v1/reference/users/messages/list
That has the URL to access (GET https://www.googleapis.com/gmail/v1/users/me/messages ) then once you have the message IDs you can get the messages individually following: https://developers.google.com/gmail/api/v1/reference/users/messages/get (e.g. GET https://www.googleapis.com/gmail/v1/users/me/messages/ ).
Usually there are good client libraries for the Google APIs. Not sure if that works for you, but see, for example:
https://developers.google.com/gmail/api/downloads

channel in trivial GAE app not getting 'onmessage'

I am trying to create the smallest possible GAE app to show the use of the channel api.
I have two handlers in the python, the first "TestPage" sends out the html shown below. The second "SendPage" tries to send a message over the channel to the test page. The code for the TestPage is
class TestPage(Handler):
def get(self):
token = channel.create_channel("1")
self.render("test.html", token = token)
It just creates the channel with an id of "1" and reders the page with the token passed back from create_channel().
The SendPage is just:
class SendPage(Handler):
def get(self):
channel.send_message("1", "hello")
self.write("sent hello to 1")
The html is as small as I could get it:
<!DOCTYPE HTML>
<html>
<body>
<br>Token is {{ token }}
<br>
<div id="debug">_</div>
<!--
<script src="https://talkgadget.google.com/talkgadget/channel.js"></script>
-->
<script src="static/channel.js"></script>
<script defer="defer">
function debug(s) {
document.getElementById("debug").innerHTML = s;
}
var channel = new goog.appengine.Channel( {{ token }} );
var socket = channel.open();
socket.onopen = function(e) {
debug("open");
}
socket.onclose = function(e) {
debug("close");
}
socket.onerror = function(e) {
debug("error");
}
socket.onmessage = function(e) {
debug("message");
}
debug("ready");
</script>
</body>
</html>
So, inside chrome I pull up TestPage and I see the "ready" message. Then I pull up the SendPage in another tab. And see the "sent message". Then when I go back to the TestPage I would expect to have "ready" replaced by "message". But this never happens. None of the socket handler functions are being called.
I'm stuck for the moment and would appreciate any help or suggestions.
Thank you.
Ok, I figured it out. There were two problems. First, the template line
var channel = new goog.appengine.Channel( {{ token }} );
should have been
var channel = new goog.appengine.Channel( "{{token}}" );
as it was token was something like "channel-2052893164-1373347311-1" which quietly evaluated to a number.
Second, the correct script for the channel.js was
<script type="text/javascript" src="/_ah/channel/jsapi"></script>
The other scripts I had referenced were from other stack overflow answers and I guess they did not properly apply to this problem.
Thanks.

Why is current_user None?

I have a horrible bug that I put a bounty on and now I'm reducing to the simplest case of reproduction. At least a can reproduce it :D Some info: The entity FUser does not populate an entity, the javascript button switches between login / logout apprioriately and from the log you might be able to tell me what's wrong with the flow.
2011-10-04 17:34:14.398 /example 200 10ms 0cpu_ms 0kb Mozilla/5.0 (X11; Linux x86_64; rv:2.0) Gecko/20100101 Firefox/4.0
213.89.134.0 - - [04/Oct/2011:13:34:14 -0700] "GET /example HTTP/1.1" 200 694 - "Mozilla/5.0 (X11; Linux x86_64; rv:2.0) Gecko/20100101 Firefox/4.0" "www.koolbusiness.com" ms=11 cpu_ms=0 api_cpu_ms=0 cpm_usd=0.000157 instance=00c61b117c837db085d58acd70ffae167a06
D 2011-10-04 17:34:14.395
logging current_userNone
.py
"""A barebones AppEngine application that uses Facebook for login."""
FACEBOOK_APP_ID = "164355773607006"
FACEBOOK_APP_SECRET = "642f15e4324b45661e1049d5b139cb0"
import facebook
import os.path
import wsgiref.handlers
import logging
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
class FUser(db.Model):
id = db.StringProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
name = db.StringProperty(required=True)
profile_url = db.StringProperty(required=True)
access_token = db.StringProperty(required=True)
class BaseHandler(webapp.RequestHandler):
"""Provides access to the active Facebook user in self.current_user
The property is lazy-loaded on first access, using the cookie saved
by the Facebook JavaScript SDK to determine the user ID of the active
user. See http://developers.facebook.com/docs/authentication/ for
more information.
"""
#property
def current_user(self):
if not hasattr(self, "_current_user"):
self._current_user = None
cookie = facebook.get_user_from_cookie(
self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
logging.debug("logging cookie"+str(cookie))
if cookie:
# Store a local instance of the user data so we don't need
# a round-trip to Facebook on every request
user = FUser.get_by_key_name(cookie["uid"])
logging.debug("user "+str(user))
if not user:
graph = facebook.GraphAPI(cookie["access_token"])
profile = graph.get_object("me")
user = FUser(key_name=str(profile["id"]),
id=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=cookie["access_token"])
user.put()
elif user.access_token != cookie["access_token"]:
user.access_token = cookie["access_token"]
user.put()
self._current_user = user
return self._current_user
class HomeHandler(BaseHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), "example.html")
logging.debug("logging current_user"+str(self.current_user))
args = dict(current_user=self.current_user,
facebook_app_id=FACEBOOK_APP_ID)
self.response.out.write(template.render(path, args))
def main():
util.run_wsgi_app(webapp.WSGIApplication([(r"/example", HomeHandler)]))
if __name__ == "__main__":
main()
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Facebook Example</title>
</head>
<body>
<fb:login-button autologoutlink="true"></fb:login-button>
{% if current_user %}
<p><img src="http://graph.facebook.com/{{ current_user.id }}/picture?type=square"/></p>
<p>Hello, {{ current_user.name|escape }}</p>
{% endif %}
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: '{{ facebook_app_id }}', status: true, cookie: true,
xfbml: true});
FB.Event.subscribe('{% if current_user %}auth.logout{% else %}auth.login{% endif %}', function(response) {
window.location.reload();
});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
Update
I still don't get the user object and changed the HomeHandler to this
class HomeHandler(BaseHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), "example.html")
logging.debug("logging current_user"+str(self.current_user))
args = dict(current_user=self.current_user,
facebook_app_id=FACEBOOK_APP_ID)
user = facebook.get_user_from_cookie(self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
if not user:
logging.debug("no user")
if user:
graph = facebook.GraphAPI(user["access_token"])
profile = graph.get_object("me")
friends = graph.get_connections("me", "friends")
logging.debug("logging profile"+str(profile))
self.response.out.write(template.render(path, args))
Relating to #Shay Erlichmen's observation, the above code shouldn't work due to facebook's changes of a few days ago. As I pointed out on your original question, there is a version of the facebook python SDK which has been modified to support the new authentication mechanism - see
https://gist.github.com/1190267
The specific place where this differs from the old version is in the get_user_from_cookie() method. If you're still using the old version of the facebook python SDK, this should look for an fbs_APPID cookie, not find it and return None - hence cookie is never assigned a value _current_user retains the None state assigned at the start of the method.
One check you can do is to have a look at the cookies in your browser - you should see the new fbsr_APPID cookies which are not handled by the old library.
Facebook switched to OAuth2.0 on October 1,2011, this code is old and should work anymore.

Resources