Authenticating Multiple Scopes in Google API Oauth2.0 - google-api

I need to insert multiple scopes into the http post request that creates the service object that permits authentication. However, simply putting in multiple scopes into the string doesn't seem to achieve this unfortunately, returning the error at the bottom.
import gflags
import apiclient
import oauth2client
import argparse
from oauth2client import client
from oauth2client import file
from oauth2client import tools
from apiclient import discovery
from apiclient import sample_tools
import httplib2
import sys
import os
import pprint
from pprint import pprint
name = 'prediction'
scope = "https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/devstorage.full_control testing_data/training_data.csv testing_data/training_data.csv"
filename = '__file__'
client_secrets = os.path.join(os.path.dirname(filename),
'client_secrets.json')
flow = client.flow_from_clientsecrets(client_secrets,scope=scope)
storage = file.Storage(name+'.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = tools.run(flow, storage)
http = credentials.authorize(httplib2.Http())
service = discovery.build('prediction','v1.6',http=http)
papi = service.trainedmodels()
result = papi.list(maxResults=10,project='895092811023').execute()
body = {'id':'Universities','storageDataLocation':'testing_data/training_data.csv'}
start = papi.insert(body=body,project='895092811023').execute()
This is the error, which points out that the required scopes are missing. (It is recording some scope, because it is saving a result to result, but just not letting me insert a new model, which I believe is due to the fact that it isn't getting the scope to access the data for this model, which is in Google Cloud Storage?
Traceback (most recent call last):
File "filehere", line 42, in <module>
start = papi.insert(body=body,project='895092811023').execute()
File "build\bdist.win-amd64\egg\oauth2client\util.py", line 132, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Python27\lib\site-packages\apiclient\http.py", line 680, in execute
raise HttpError(resp, content, uri=self.uri)
HttpError: <HttpError 401 when requesting https://www.googleapis.com/prediction/v1.6/projects/895092811023/trainedmodels?alt=json returned "Required scope(s) missing.">

The only thing you need to pass in for scopes are the www.googleapis.com things such as: https://www.googleapis.com/auth/prediction, don't pass in "testing_data/training_data.csv testing_data/training_data.csv".
You can always visit https://accounts.google.com/b/0/IssuedAuthSubTokens and see the scopes that your application has been granted.

Related

Http Post Request - TypeError: 'Response' object is not subscriptable

I'm trying to write a request for an api to pull a csv for trade histories. I'm having an issue when it gets to the actual request and I'm not sure whether its a client issue, something to do with the libraries, or the way I'm making the request itself. The API is hosted on dYdX's servers and there are a few dependencies -I've follow most of the docs (https://docs.dydx.exchange/).
Here are the imports:
from dydx3 import Client
from dydx3 import constants
from dydx3 import epoch_seconds_to_iso
from os import path
import ciso8601
import datetime
import pprint
import subprocess
import sys
import time
import json
and here is the client initialization and request:
client2 = Client(
host = _api_host,
network_id = _network_id,
api_key_credentials = {
'key': _api_key,
'secret': _api_secret,
'passphrase': _api_passphrase
}
)
get_account_result2 = client2.private.get_account(
ethereum_address = _eth_address
)
account2 = get_account_result2['account']
It keeps crashing on the line with account2 = get_account_result2['account'], TypeError: 'Response' object is not subscriptable. I've run it through Windows and Linux (Ubuntu) Python 3. I feel like it's a syntax thing with the json? Is there something I'm missing?
You are trying to access the ‘account’ value of that Response object as if it’s a dictionary object (subscriptable) but it is not. The good news is it likely has a method to show you the response in json, text or dictionary from.
To see which methods or attributes the Response object has try:
dir(get_account_result2)
If there is a "json" method in that list, you might want to try:
get_account_result2.json()[‘account’]
If there is an "account" attribute (not callable) or method (callable) respectively, you could also try:
get_account_result2.account or get_account_result2.account()
I dont have a dydx account so I cannot verify if any of this works.

How to pass MQTT message object (including topic and payload) from on_message callback function across django using queue?

I am developing a Django Rest API project to read sensors' data and display their realtime values in the browser.
I have an __init__.py file inside the utils folder that initiates the MQTT connection and subscribes to the sensor topics.
import paho.mqtt.client as mqtt
from device.models import Device, RecordLog
import datetime
from queue import Queue
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
# client.subscribe("$SYS/#")
for topic in Device.object.values_list('unique_id', flat=True):
client.subscribe(topic)
q = Queue()
message_list = []
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload.decode('utf-8')))
message_list.append(msg)
q.put(message_list)
#insert into database
try:
r = RecordLog(device=Device.objects.filter(unique_id=msg.topic).values_list('name', flat=True).first(), topic=msg.topic, record=str(msg.payload.decode('utf-8')), dt_inserted=datetime.datetime.now())
r.save()
except:
print("Error on storing data into database")
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("mqtt.eclipse.org", 1883, 60)
client.loop_start()
Using this piece of code I insert the sensor's data into the database and I want to put them into a queue and call them in views.py.
from utils import on_message, on_connect
from queue import Queue
q = Queue()
# MQTT Data Serializer
class Sensor:
permission_classes = (permissions.IsAuthenticated,)
serializer_class = DeviceSerializer
def pusher(self):
queryset = Device.objects.filter(unique_id=q.get().topic).values_list('place', 'name', 'device_type', 'unique_id')
data = {
"device_info": queryset,
"sensor_data": q.get().payload
}
return JsonResponse(data)
and my urls.py is...
from .views import Sensor
urlpatterns = [
path('device/sensors/', Sensor.pusher),
]
But finally, my endpoint URL remains to load and returns no response.
I will be grateful if you help me to solve this problem or make an alternative solution.

Unable to start a Session in Flask within a function

I'm running Flask Session and using Eve as an API. For the Session code I'm following the example here https://pythonhosted.org/Flask-Session/
from flask import Flask, session
from flask.ext.session import Session
app = Flask(__name__)
# Check Configuration section for more details
SESSION_TYPE = 'redis'
app.config.from_object(__name__)
Session(app)
#app.route('/set/')
def set():
session['key'] = 'value'
return 'ok'
#app.route('/get/')
def get():
return session.get('key', 'not set')
I have an Eve API located under /api, and I want to avoid starting a new Session for those requests at least.
I want to start my flask Session only if the request.environ['PATH_INFO'] doesn't start with '/api/' but whenever I put Session() anywhere else it fails.
Following the example:
sess = Session()
sess.init_app(app)
When I try to do that in before_request or similar, then I get:
A setup function was called after the first request was handled.
and if I try to start a session in a normal content generator I get:
AttributeError: 'SecureCookieSession' object has no attribute 'sid'
How can I start a session conditionally, depending on the path/environment/etc?
My current code looks like this:
import flask
import xml.etree.ElementTree as ElementTree
from bson.objectid import ObjectId
from random import shuffle, choice as pick
from cgi import escape as escapehtml
from time import mktime
from urllib import quote as escapeurl, unquote_plus as unescapeurl
from flask import Flask, request, session, render_template, send_from_directory, jsonify, redirect, abort
from flask.ext.session import Session
from flask.ext.login import LoginManager, login_user, logout_user, current_user, UserMixin, user_logged_in, login_required, fresh_login_required
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired, URLSafeTimedSerializer
from flask_mail import Mail, Message
from wtforms import Form, BooleanField, PasswordField
from flask.ext.mongoengine import MongoEngine
from flask.ext.security import Security, MongoEngineUserDatastore, RoleMixin, UserMixin
from flask.ext.principal import Principal, Permission, RoleNeed
from flask_security.forms import RegisterForm, Required, StringField
from flask_images import Images
from eve import Eve
from eve.auth import TokenAuth
from flask.ext.moment import Moment
from eve.io.mongo import Validator
from flask.ext.cors import CORS, cross_origin
from app.admin.one1 import one1
from app.emails.emails import emails
from app.alligator.alligator import alligator
from app.data.ndm_feed.ndm_feed import ndm_feed
from flask.ext import excel
...
login_serializer = URLSafeTimedSerializer(app.secret_key)
login_manager = LoginManager()
app.config.from_object(__name__)
login_manager.init_app(app)
Session(app)
and to avoid starting sessions for API calls I am trying to do things like this:
#app.before_request
def before_request():
if not request.environ['PATH_INFO'].startswith('/api/'):
Session(app)
or the equivalent:
#app.before_request
def before_request():
if not request.environ['PATH_INFO'].startswith('/api/'):
sess = Session()
sess.init_app(app)
But I can't seem to find a way to do it without the errors above.
How can I start a Flask session conditionally, depending on the path/environment/etc?
Actually your app already created before you use this: #app.before_request so it means you are late to add new configuration or extension initialize. Bu you can do with Blueprint:
# api.py
from flask import Blueprint
from flask_session import Session
sess = Session()
api = Blueprint('api', __name__)
# yourapp.py
...
def create_app():
...
try:
from api import api, sess
sess.init_app(app)
app.register_blueprint(api)
# views.py
#api.route('/set/')
def set():
session['key'] = 'value'
return 'ok

upload several images in a post to twitter with tweepy library

to update with a image there is no problem. This is the code and it wotks:
import tweepy
from subprocess import call
from datetime import datetime
import time
...key and tokens...
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
photo_path = '/directory/image.jpg'
status = 'Subject o text'
api.update_with_media(photo_path, status=status)
but what if i want post a tweet with multiple images? it is posible to do that with this library?
Because update_with_media endpoint is deprecated by Twitter, you should use media_upload like this:
api = tweepy.API(auth)
images = ('image1.png', 'image2.png')
media_ids = [api.media_upload(i).media_id_string for i in images]
status = 'Subject o text'
api.update_with_media(media_ids=media_ids, status=status)

Okta api python sdk throwing json error

I'm trying to create a user with the python sdk. When I run my script, I get the following error:
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/sitepackages/oktasdk-python/okta/framework/ApiClient.py", line 53, in post
if self.__check_response(resp, attempts):
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/sitepackages/oktasdk-python/okta/framework/ApiClient.py", line 88, in __check_response
raise OktaError(json.loads(resp.text))
okta.framework.OktaError.OktaError: The request body was not well-formed: Could not read JSON
Here is a snippet of my code:
from okta.UsersClient import UsersClient
from collections import namedtuple
def main():
create_okta_user()
def create_okta_user():
usersClient = UsersClient("https://example.okta.com", "0d0d0dexamplekey")
User = namedtuple("User", ["login", "email", "firstName", "lastName"], verbose=False, rename=False)
user = User(login="test#example.com",
email="test#example.com",
firstName="user",
lastName="tester")
usersClient.create_user(user, activate=False)
#usersClient.activate_user(user)
main()
It looks like you're trying to use a namedtuple, which is serialized to a json list, not an object.
Try using the User model like this:
from okta import UsersClient
from okta.models.user import User
def main():
create_okta_user()
def create_okta_user():
usersClient = UsersClient("https://example.okta.com", "0d0d0dexamplekey")
user = User(login="test#example.com",
email="test#example.com",
firstName="user",
lastName="tester")
user = usersClient.create_user(user, activate=False)
#usersClient.activate_user(user)
main()
http://developer.okta.com/docs/sdk/core/python_api_sdk/quickstart.html#create-a-user

Resources