run_flow complains about getting its minimum three arguments - python-2.7

I'm working on a simple script to send emails via the GMail API, and an old script I found to access their SMTP interface wasn't working.
So I used the following script from their quickstart page to start first with reading:
#! /usr/bin/env python
#
import httplib2
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run
CLIENT_SECRET = '.client.json'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.readonly'
STORAGE = Storage('gmail.storage')
flow = flow_from_clientsecrets(CLIENT_SECRET, scope=OAUTH_SCOPE)
http = httplib2.Http()
credentials = STORAGE.get()
if credentials is None or credentials.invalid:
credentials = run(flow, STORAGE, http=http)
http = credentials.authorize(http)
gmail_service = build('gmail', 'v1', http=http)
threads = gmail_service.users().threads().list(userId='me').execute()
if threads['threads']:
for thread in threads['threads']:
print 'Thread ID: %s' % (thread['id'])
Running this gives a NotImplementedError as shown in this question.
So I imported and called run_flow instead of run, as I did not install gflags to continue. However, I get the following error:
TypeError: run_flow() takes at least 3 arguments (3 given)
I understand from the linked question that argparse should help. I could add the call to parser that that question uses, but I would have no idea what arguments to pass on the command line.
Anyone successfully implemented something with this who could give some help?

You don't need to pass extra arguments to the command line when using run_flow python.
import argparse
...
from oauth2client import tools
...
from oauth2client.tools import run_flow
...
parser = argparse.ArgumentParser(parents=[tools.argparser])
flags = parser.parse_args()
....
credentials = run_flow(flow, STORAGE, flags, http=http)
Then you can run
python quickstart.py

Related

Django Rest Framework with Firebase Firestore - API endpoint returns NoneType due to initialize_app runs more than once

I'm trying to build a read-only API that fetches its data from Firebase, Firestore. I'm having an issue when I request any endpoint in my API, multiple times, I get an error.
I won't include Django related files and classes. So, here are the code pieces you need to know.
firebase_initilizer.py
import firebase_admin
from firebase_admin import credentials, firestore
if not firebase_admin._apps:
cred = credentials.Certificate('./FILE_PATH.json')
firebase_admin.initialize_app(cred)
db = firestore.client()
collection_ref = db.collection(u"collection-name")
docs = collection_ref.stream()
views.py [A simplified version of what I use in one of my API endpoints]
class Contact(APIView):
"""
Returns the user's contact details.
"""
def get(self, request, uid, format="json"):
for doc in docs:
if uid == doc.id:
return Response(data=doc.to_dict()["contact"], status=status.HTTP_200_OK)
Again, the issue is that I get an error saying "NoneType" whenever I request any endpoint more than once. At this point, I can run my API only once.
The error:
AssertionError at /api/v1/contact/
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
"GET /api/v1/contact/ HTTP/1.1" 500 78864
From what I know, I need to initialize Firebase only once. Then, I only need to request whatever I want by using the variable I assigned the Firebase reference. However, I don't know how to do it
I solved my problem by inserting my firebase initializer code piece into manage.py. Plus, it also works in settings.py.
For example, the manage.py file can be rearranged as follows:
import os, sys
import firebase_admin
from firebase_admin import credentials, firestore
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings')
try:
from django.core.management import execute_from_command_line
if not firebase_admin._apps:
cred = credentials.Certificate('./FILE_PATH.json')
firebase_admin.initialize_app(cred)
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
or you can simply add the following lines to anywhere in settings.py:
import firebase_admin
from firebase_admin import credentials
if not firebase_admin._apps:
cred = credentials.Certificate('./FILE_PATH.json')
firebase_admin.initialize_app(cred)
I hope this answer helps others.

How to authenticate DCM account by using service account?

I'm trying to download the report from DCM by using python client library. I'm using service account and using this link code this!. I have followed all the steps to set up the service account file which is mentioned in DCM api url, but I'm getting below error while running the code.
Traceback (most recent call last):
File "/usr/bin/anaconda/envs/py35/lib/python3.5/site-packages/oauth2client/clientsecrets.py", line 86, in _validate_clientsecrets
(client_type, client_info), = clientsecrets_dict.items()
ValueError: too many values to unpack (expected 1)
I'm using below service account file to connect to the DCM api and download the reports. This is the process I'm trying to set up so that on daily basis the reports get download automatically without any manual intervention.
import argparse
import sys
from googleapiclient import discovery
import httplib2
from oauth2client import client
from oauth2client import tools
from oauth2client.service_account import ServiceAccountCredentials
# Declare command-line flags.
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument('path_to_service_account_json_file',help='Path to the service account JSON file to use for authenticating.')
argparser.add_argument('-i','--impersonation_email',help='Google account email to impersonate.')
# The OAuth 2.0 scopes to request.
OAUTH_SCOPES = ['https://www.googleapis.com/auth/dfareporting']
def main(argv):
# Retrieve command line arguments.
parser = argparse.ArgumentParser(description=__doc__,formatter_class=argparse.RawDescriptionHelpFormatter,parents=[tools.argparser, argparser])
flags = parser.parse_args(argv[1:])
# Authenticate using the supplied service account credentials
http = authenticate_using_service_account(flags.path_to_service_account_json_file,flags.impersonation_email)
# Construct a service object via the discovery service.
service = discovery.build('dfareporting', 'v3.3', http=http)
try:
# Construct the request.
request = service.userProfiles().list()
# Execute request and print response.
response = request.execute()
for profile in response['items']:
print('Found user profile with ID %s and user name "%s".' %(profile['profileId'], profile['userName']))
except client.AccessTokenRefreshError:
print('The credentials have been revoked or expired, please re-run the ''application to re-authorize')
def authenticate_using_service_account(path_to_service_account_json_file,impersonation_email):
"""Authorizes an httplib2.Http instance using service account credentials."""
# Load the service account credentials from the specified JSON keyfile.
credentials = ServiceAccountCredentials.from_json_keyfile_name(path_to_service_account_json_file,scopes=OAUTH_SCOPES)
# Configure impersonation (if applicable).
if impersonation_email:
credentials = credentials.create_delegated(impersonation_email)
# Use the credentials to authorize an httplib2.Http instance.
http = credentials.authorize(httplib2.Http())
return http
if __name__ == "__main__":
main(sys.argv)
TypeError: cannot instantiate ctype 'EVP_MD_CTX' of unknown size

Run RASA with flask

I want to run RASA with --enable-api inside the python code rather than the command line. Below is my code which is not working. Let me know how can i do that. The issue is once i hit the service because the channel is 'cmdline' it comes to the command line. I don't know how to resolve this.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import rasa_core
from rasa_core.agent import Agent
from rasa_core.policies.keras_policy import KerasPolicy
from rasa_core.policies.memoization import MemoizationPolicy
from rasa_core.interpreter import RasaNLUInterpreter
from rasa_core.utils import EndpointConfig
from rasa_core.run import serve_application
from rasa_core import config
from rasa_core.policies.fallback import FallbackPolicy
from rasa_core.policies.keras_policy import KerasPolicy
from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
logger = logging.getLogger(__name__)
#app.route("/conversations/default/respond",methods=['POST'])
def run_weather_bot(serve_forever=True):
logging.basicConfig(level="ERROR")
interpreter = RasaNLUInterpreter('C:\\xxxx_nlu\\models\\nlu\\default\\weathernlu')
action_endpoint = EndpointConfig(url="http://xxx.xx.xx.xxx:5055/webhook")
agent = Agent.load('C:\\xxxx_nlu\\models\\dialogue', interpreter=interpreter, action_endpoint=action_endpoint)
rasa_core.run.serve_application(agent,channel='cmdline')
return agent
if __name__ == '__main__':
app.run("xxx.xx.xx.xxx",5005,debug=True)
You're calling rasa bot in the command line in your run_weather_bot function using below command.
rasa_core.run.serve_application(agent,channel='cmdline')
As you can see its serving as command line application.
I have made some changes in your code for a conversation with rasa chatbot. You can refer AGENT documentation and Weather bot article for connection of RASA agent and how RASA agent handles the input message.
def rasa_agent():
interpreter = RasaNLUInterpreter("Path for NLU")
action_endpoint = EndpointConfig(url="Webhook URL")
agent = Agent.load('Path to Dialogue', interpreter=interpreter, action_endpoint=action_endpoint)
## Next line runs the rasa in commandline
# rasa_core.run.serve_application(agent,channel='cmdline')
return agent
#app.route("/conversations/default/respond",methods=['POST'])
def run_weather_bot(serve_forever=True):
agent = rasa_agent() # calling rasa agent
## Collect Query from POST request
## Send Query to Agent
## Get Response of BOT
output = {} ## Append output
return jsonify(output)

My webservice with oauth2client don't work on remote server,

The django app runs on the local server, but does not work on the remote.
The server does not have a GUI and does not provide the user with a link to authorization. The server outputs link to the console.
from __future__ import print_function
from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
import datetime
import os
import json
SCOPES = 'https://www.googleapis.com/auth/calendar'
from .models import Aim
try:
import argparse
flags = tools.argparser.parse_args([])
except ImportError:
flags = None
def calendar_authorization(username):
store = open('app/static/secret_data/' + username +'.json', 'w')
store.close()
store = file.Storage('app/static/secret_data/' + username +'.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('app/client_secret.json', SCOPES)
flags.noauth_local_webserver = True
print("________flow_______")
print(flow.__dict__)
creds = tools.run_flow(flow, store, flags)
print("________creds_______")
print(creds.__dict__)
In the local version, I use client_secret.json, obtained from OAuth 2.0 client IDs. I suspect that I may have the wrong settings for this.
I found the information to use the Service account keys(I don't use it now). But I didn’t find a good setup guide for this.
How to set it up and paste in the code for authorization(
I did not understand how the access service key is used in the code?)?
What could be wrong?

Invalid syntax error in google python api

I am new to google python api client.I am learning from https://developers.google.com/api-client-library/python/start/get_started.I want to make an api which converts python object into JSON data and sends to a servlet.
The python code of file api.py:
import os
import urllib2
import httplib2
import json
import requests
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run_flow
from oauth2client.file import Storage
from oauth2client import tools
api_version='1'
_file_="D:\API"
CLIENT_SECRETS = os.path.join(os.path.dirname(_file_))
flow=flow_from_clientsecrets(CLIENT_SECRETS,
scope=[
'https://www.googleapis.com/auth/devstorage.full_control',
],
http = httplib2.Http()
auth_http = credentials.authorize(http)
service=build('SendNotif',api_version,http=http)
req = urllib2.Request('http://example/notify')
req.add_header('Content-Type', 'application/json')
data={"message":"Hello User you are notified"}
data_json = json.dumps(data)
response = urllib2.urlopen(req, json.dumps(data))
The error shown is:
D:\API>python api.py
File "api.py", line 25
auth_http = credentials.authorize(http)
^
SyntaxError: invalid syntax
please do help in correcting me..
thanks in advance....
You're missing a closing parenthesis for this line:
flow=flow_from_clientsecrets(CLIENT_SECRETS,