Cannot find reference 'discovery' in '__init__.py' Google custom search API - python

while following this tutorial : https://www.youtube.com/watch?v=IBhdLRheKyM
I ran into a problem and i've tried several things like replacing apiclient.discovery with googleapiclient.discovery.
Didn't work.
type(resource) and len(result['items'] return void.
PyCharm states that there an unresolved reference.
Cannot find reference 'discovery' in '__init__.py'
i installed the module using the pip tool. (pip install google-api-python-client) which prompted no issues whatsoever.
Example code:
from apiclient.discovery import build
api_key = "api_key"
resource = build("customsearch", 'v1', developerKey=api_key).cse()
result = resource.list(q='alfa romeo', cx="searchengineID").execute()
type(resource)
len(result['items'])
>> Process finished with exit code 0
edited out the api_key and cx as it's sensitive information.
'init.py' source:
"""Retain apiclient as an alias for googleapiclient."""
from six import iteritems
import googleapiclient
from googleapiclient import channel
from googleapiclient import discovery
from googleapiclient import errors
from googleapiclient import http
from googleapiclient import mimeparse
from googleapiclient import model
try:
from googleapiclient import sample_tools
except ImportError:
# Silently ignore, because the vast majority of consumers won't use it and
# it has deep dependence on oauth2client, an optional dependency.
sample_tools = None
from googleapiclient import schema
__version__ = googleapiclient.__version__
_SUBMODULES = {
'channel': channel,
'discovery': discovery,
'errors': errors,
'http': http,
'mimeparse': mimeparse,
'model': model,
'sample_tools': sample_tools,
'schema': schema,
}
import sys
for module_name, module in iteritems(_SUBMODULES):
sys.modules['apiclient.%s' % module_name] = module

Hmm. Pasting that exact code (replacing the API key and CX) worked for me into a shell worked for me in both Python 2.7 and 3.5.
Normally if apiclient.discovery.build() fails, it will raise an exception, rather than returning an invalid value.
What do you mean when you say "type(resource) and len(result['items'] return void"? As void isn't a type in Python, did you mean <class 'NoneType'>?
Also, what does type(result) return?

Related

Unable to import module 'app': No module named 'app' in Aws Lambda using Chalice

I am having below lambda function which uses Chalice.
from chalice import Chalice
from chalicelib import lookup_helper
import os
try:
from urllib import unquote
except ImportError:
from urllib.parse import unquote
app = Chalice(app_name='some_app')
#app.route('/some_route', methods=['GET'])
def some_func(arg):
//some code
When I test this function I get below error
{"errorMessage": "Unable to import module 'app': No module named 'app'", "errorType": "Runtime.ImportModuleError"}
Tue Sep 22 11:59:10 UTC 2020 : Lambda execution failed with status 200 due to customer function error: Unable to import module 'app': No module named 'app'.
Can anyone please help me out here.
Python - 3.7
Update--
from chalice import Chalice
import os
app = Chalice(app_name='some_app')
#app.route('/some_route', methods=['GET'])
def some_func(arg):
return {}
Reduced the function to above. Still same error.
When I checked the pipeline (azure devops), I see below error in the logs, though the step passes as a whole.
FileExistsError: [Errno 17] File exists: 'build/lambda/requests'
requirement.txt
requests==2.22.0
see https://chalice-workshop.readthedocs.io/en/latest/media-query/00-intro-chalice.html
Add a new function hello_world decorated by app.lambda_function() that
returns {"hello": "world"}. Your app.py file should now consist of the
following lines:
from chalice import Chalice
app = Chalice(app_name='workshop-intro')
#app.lambda_function()
def hello_world(event, context):
return {'hello': 'world'}
What is the name of you python file. Is it 'app.py' ?

How to resolve this: pyreportjasper: ImportError: DLL load failed while importing jpy: The specified module could not be found

I want to use Jasper Reports with a python-flask app.
I have followed the installation instructions on this page:
https://pypi.org/project/pyreportjasper/
It fails on the line import jpy, I am getting the error:
ImportError: DLL load failed while importing jpy: The specified module could not be found.
I am using 32 bit python Python: 3.8.6rc1.
32 bit JDK: javac 1.8.0_261
When I run pip install pyreportjasper, it says: Requirement already satisfied: jpy in c:\users....
Any ideas?
It seems that you need to import jpyutil and then initialize the JVM prior to calling import jpy. The following fixed this error for me. One step closer.
import jpyutil
jpyutil.init_jvm(jvm_maxmem='512M')
import jpy
UPDATE: so while the above statement is true, it doesn't directly address the issue of running the example code at the project page: https://pypi.org/project/pyreportjasper/
As I dug into the code I found that jasperpy.py is attempting to import jpy BEFORE the __init__ method is run and therefore BEFORE the JVM is initialized via the jpyutil.init_jvm() method call. So I edited jasperpy.py and moved import jpy from line 14 to line 56, directly after the call to jpyutil.init_jvm() and before the call to jpy.get_type('java.io.File') and I am able to successfully run Jasper reports from python via the example code shown. Here is what my jasperpy.py looks like now.
# -*- coding: utf-8 -*-
# GNU GENERAL PUBLIC LICENSE
#
# Copyright (c) 2020 Jadson Bonfim Ribeiro <contato#jadsonbr.com.br>
#
import os
import subprocess
import re
import xml.etree.ElementTree as ET
import tempfile
import jpyutil
#import jpy
import json
from requests import Request, Session
FORMATS = (
'pdf',
'rtf',
'xls',
'xlsx',
'docx',
'odt',
'ods',
'pptx',
'csv',
'html',
'xhtml',
'xml',
'jrprint',
)
EXECUTABLE = 'jasperstarter'
class JasperPy:
_FORMATS_JSON = ('pdf')
_FORMATS_METHODS_REQUEST = ('GET', 'POST', 'PUT')
def __init__(self, resource_dir=False, jvm_maxmem='512M', jvm_classpath=None):
self.WINDOWS = True if os.name == 'nt' else False
self.SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
self.LIBS = os.path.join(self.SCRIPT_DIR, 'jasperstarter', 'lib')
if not os.path.isdir(self.LIBS):
raise NameError('Unable to find lib in {0}'.format(self.LIBS))
self.CLASSPATH = os.path.join(self.LIBS, 'jasperstarter.jar')
if not os.path.exists(self.CLASSPATH):
raise NameError('Unable to find jasperstarter in {0}'.format(self.LIBS))
if jvm_classpath is None:
jpyutil.init_jvm(jvm_maxmem=jvm_maxmem, jvm_classpath=[self.CLASSPATH])
else:
jpyutil.init_jvm(jvm_maxmem=jvm_maxmem, jvm_classpath=[self.CLASSPATH, jvm_classpath])
# IMPORT jpy HERE AFTER init_jvm
import jpy
self.jvFile = jpy.get_type('java.io.File')
self.jvArrays = jpy.get_type('java.util.Arrays')
self.jvReport = jpy.get_type('de.cenote.jasperstarter.Report')
self.jvConfig = jpy.get_type('de.cenote.jasperstarter.Config')
self.jvDsType = jpy.get_type('de.cenote.jasperstarter.types.DsType')
self.jvApplicationClasspath = jpy.get_type('de.cenote.tools.classpath.ApplicationClasspath')
self.jvHashMap = jpy.get_type('java.util.HashMap')
self.jvLocale = jpy.get_type('java.util.Locale')
self.jvJasperFillManager = jpy.get_type('net.sf.jasperreports.engine.JasperFillManager')
self.jvDb = jpy.get_type('de.cenote.jasperstarter.Db')
self.jvJsonQueryExecuterFactory = jpy.get_type('net.sf.jasperreports.engine.query.JsonQueryExecuterFactory')
self.jvJasperExportManager = jpy.get_type('net.sf.jasperreports.engine.JasperExportManager')
.
.
.
.
This file is located in your Python directory under Lib\site-packages\pyreportjasper-2.0.2-py3.8.egg\pyreportjasper. While this is currently a hack to make it work, there obviously needs to be a fix to the package which I will attempt to address on the pyreportjasper github page.

importerror watson_developer_cloud Python

I have pip installed watson-developer-cloud, on python v3.5
I am simply trying to run one of the example codes: alchemy_data_news_v1.py
Link:https://github.com/watson-developer-cloud/python-sdk/tree/master/examples
import json
from watson_developer_cloud import AlchemyLanguageV1
alchemy_data_news = AlchemyDataNewsV1(api_key='api-key')
results = alchemy_data_news.get_news_documents(start='now-7d', end='now',
time_slice='12h')
print(json.dumps(results, indent=2))
results = alchemy_data_news.get_news_documents(
start='1453334400',
end='1454022000',
return_fields=['enriched.url.title',
'enriched.url.url',
'enriched.url.author',
'enriched.url.publicationDate'],
query_fields={
'q.enriched.url.enrichedTitle.entities.entity':
'|text=IBM,type=company|'})
print(json.dumps(results, indent=2))
I have also tried utilizing my own personal api-key and the result is the same:
File "c:\users\Joseph Sansevero\desktop\test.py", line 2, in
watson_developer_cloud import AlchemyLanguageV1 ImportError: No module
named watson_developer_cloud
Change your import statement to
from watson_developer_cloud import AlchemyLanguageV1
Alchemy language is a different api than AlchemyNews.
Head over to https://www.ibm.com/watson/developercloud/alchemydata-news/api/v1/?python#methods and you'll see the example has AlchemyNews imported.
Also make sure you install these packages using before running your code.

Why am I still getting the error: "CryptoUnavailableError: No crypto library available" in Python?

I am trying to make an API call through Python to Google's DFA and am using their suggested code. However, it is still not saying the credentials object is defined and throws the error:
Traceback (most recent call last):
File "<input>", line 2, in <module>
File "C:\Python27\lib\site-packages\oauth2client\util.py", line 137, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Python27\lib\site-packages\oauth2client\client.py", line 1502, in __init__
_RequireCryptoOrDie()
File "C:\Python27\lib\site-packages\oauth2client\client.py", line 1456, in _RequireCryptoOrDie
raise CryptoUnavailableError('No crypto library available')
CryptoUnavailableError: No crypto library available
I have installed the pyOpenSSL library, and pycrypto library with the VCForPython compiler. I have also managed to edit all 3 app.yaml files in the LiClipse client to append:
libraries:
- name: pycrypto
version: "latest"
onto it.
This is what my code looks like so far with arbitrary credentials:
import json
import sys
import apiclient
from oauth2client import crypt
import ssl
import urllib2
from OpenSSL import crypto
HAS_OPENSSL = False
HAS_CRYPTO = False
try:
from oauth2client import crypt
HAS_CRYPTO = True
if crypt.OpenSSLVerifier is not None:
HAS_OPENSSL = True
except ImportError:
pass
from oauth2client.client import SignedJwtAssertionCredentials
client_email = 'example.apps.googleusercontent.com'
with open("C:\My Project-1234.p12") as f:
private_key = f.read()
credentials = SignedJwtAssertionCredentials(client_email, private_key,
'https://www.googleapis.com/auth/dfareporting')
from httplib2 import Http
I realize there is probably some excess in the beginning. I have not been able to get past this step.
I feel like I have tried everything and am still getting thrown the 'no crypto library' error.
Can anyone help? THANK YOU!
PS - I am using Windows 7 and Python 2.7 and LiClipse.
The above method was to make an API call as a 'service' Google account. I retried as an 'installed application' account with new credentials and a different way to make the API call which did not require any crypto type libraries.

Check which module imported

I am running an app on Google app engine that uses urlfetch in production, but uses requests locally. For example:
try:
import urlfetch
except:
import requests
The two modules act differently, so it's not as easy as just aliasing it, like json vs simplejson. How would I tell which module I have imported? For example, something like:
if 'urlfetch' loaded:
urlfetch(method='post', url='url', ...)
else:
requests.post(url)
You can use sys.modules to see which modules have been imported. For example:
>>> import sys; reload(sys)
>>> 'urlfetch' in sys.modules
True

Categories