ImportError: cannot import name SignedJwtAssertionCredentials using AppEngine dev server - python

When I do :
from oauth2client.client import SignedJwtAssertionCredentials
in my main.py which is served using the App Engine development server, I am getting an error :
ImportError: cannot import name SignedJwtAssertionCredentials
When I ran from a standard python console the same statement, I am not getting any error. The import works fine.
I confirm that I have pyopenssl installed on my system. I have already read this post which suggest only to install it: ImportError: cannot import name SignedJwtAssertionCredentials
Any idea of what's wrong with the development server?
PS : My main goal is to connect to BigQuery

Instead of using SignedJwtAssertionCredentials and deploying your PKCS12 key with your application, you can use AppAssertionCredentials from the oauth2client.appengine package. Ensure that your appengine application service is added to your project and you are good to go.
Looks like a long standing issue with the AppEngine environment: https://code.google.com/p/google-api-python-client/issues/detail?id=133

Related

Flask app wont launch 'ImportError: cannot import name 'cached_property' from 'werkzeug' '

I've been working on a Flask app for a few weeks. I finished it today and went to deploy it... and now it won't launch.
I haven't added or removed any code so assume something has changed in the deployment process?
Anyway, here is the full error displayed in the terminal:
Traceback (most recent call last):
File "C:\Users\Kev\Documents\Projects\Docket\manage.py", line 5, in <module>
from app import create_app, db
File "C:\Users\Kev\Documents\Projects\Docket\app\__init__.py", line 21, in <module>
from app.api import api, blueprint, limiter
File "C:\Users\Kev\Documents\Projects\Docket\app\api\__init__.py", line 2, in <module>
from flask_restplus import Api
File "C:\Users\Kev\.virtualenvs\Docket-LasDxOWU\lib\site-packages\flask_restplus\__init_
_.py", line 4, in <module>
from . import fields, reqparse, apidoc, inputs, cors
File "C:\Users\Kev\.virtualenvs\Docket-LasDxOWU\lib\site-packages\flask_restplus\fields.
py", line 17, in <module>
from werkzeug import cached_property
ImportError: cannot import name 'cached_property' from 'werkzeug' (C:\Users\Kev\.virtualen
vs\Docket-LasDxOWU\lib\site-packages\werkzeug\__init__.py)
Also here's the code in the three files mentioned.
manage.py:
from apscheduler.schedulers.background import BackgroundScheduler
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import create_app, db
app = create_app()
app.app_context().push()
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
from app.routes import *
from app.models import *
def clear_data():
with app.app_context():
db.session.query(User).delete()
db.session.query(Todo).delete()
db.session.commit()
print("Deleted table rows!")
#manager.command
def run():
scheduler = BackgroundScheduler()
scheduler.add_job(clear_data, trigger='interval', minutes=15)
scheduler.start()
app.run(debug=True)
if __name__ == '__main__':
clear_data()
manager.run()
app/__init__.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from config import Config
db = SQLAlchemy()
login = LoginManager()
def create_app():
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
login.init_app(app)
login.login_view = 'login'
from app.api import api, blueprint, limiter
from app.api.endpoints import users, todos, register
from app.api.endpoints.todos import TodosNS
from app.api.endpoints.users import UserNS
from app.api.endpoints.register import RegisterNS
api.init_app(app)
app.register_blueprint(blueprint)
limiter.init_app(app)
api.add_namespace(TodosNS)
api.add_namespace(UserNS)
api.add_namespace(RegisterNS)
return app
api/__init__.py:
from logging import StreamHandler
from flask_restplus import Api
from flask import Blueprint
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
blueprint = Blueprint('api', __name__, url_prefix='/api')
limiter = Limiter(key_func=get_remote_address)
limiter.logger.addHandler(StreamHandler())
api = Api(blueprint, doc='/documentation', version='1.0', title='Docket API',
description='API for Docket. Create users and todo items through a REST API.\n'
'First of all, begin by registering a new user via the registration form in the web interface.\n'
'Or via a `POST` request to the `/Register/` end point', decorators=[limiter.limit("50/day", error_message="API request limit has been reached (50 per day)")])
I've tried reinstalling flask & flask_restplus but no-luck.
The proper answer for May 2020: flask-restplus is dead, move to flask-restx.
From noirbizarre/flask-restplus#778 (comment):
flask-restplus work has been discontinued due to maintainers not having pypi keys. See the drop in replacement, flask-restx. It's an official fork by the maintainer team. We have already fixed the issue there
From noirbizarre/flask-restplus#777 (comment):
No. Flask-restplus is no longer maintained. The former maintainers do not have privileges to push to pypi, and after many months of trying, we forked the project. Check out flask-restx. It's a drop in replacement and we are roadmapping, designing, and making fixes...for instance, we already patched for Werkzeug
So the real solution is to move to flask-restx rather than pinning to an old version of Werkzeug.
Downgrading to Werkzeug==0.16.1 solves this
see https://github.com/noirbizarre/flask-restplus/issues/777#issuecomment-583235327
EDIT
Wanted to add that a permanent(long term) solution would be to move to flask_restx as flask-restplus is no longer being maintained.
See how to migrate from flask-restplus
Try:
from werkzeug.utils import cached_property
https://werkzeug.palletsprojects.com/en/1.0.x/utils/
Downgrade Werkzeug to 0.16.1
pip3 install --upgrade Werkzeug==0.16.1
If you do a pip3 list you may see something like this:
Flask 1.1.2
Werkzeug 0.16.1
For fix this painful bug was to identify what happen after the installation of the new package in the file PipFile.lock was to do a diff file and find the differences:
What I found after the installation of the package was the werkzeug package change her version of "version": "==0.15.2" to "version": "==1.0.1" and when try to excute the command sudo docker-compose build give me the error.
To fix this error this is what I did:
Discard all the change and start again.
Stop and remove your previous docker
sudo docker stop $(sudo docker ps -aq)
sudo docker rm $(sudo docker ps -aq)
Execute again the docker:
sudo docker-compose build
sudo docker-compose up
Go inside of the docker , get the id of the docker : first press CRTL+z to pause the docker and after in the terminal execute
sudo docker ps
Get the number of the CONTAINER ID column
execute : sudo docker exec -it 23f77dbefd57 bash for enter in terminal of the docker
Now execute the package that you want in my case is SOAPpy, like this
`pipenv install SOAPpy`
And after this instalation, install the previous package of the werkzeug package in my case is
pipenv install Werkzeug==0.15.2
write exit and press "Enter" in the terminal, for close the terminal inside the docker.
If you compare the files Pipfile.lock have the same version, this is the real fix.
for final steps is to do : stop , build and up the docker again:
sudo docker stop $(sudo docker ps -aq)
sudo docker-compose build
sudo docker-compose up
Now is running again the docker:
A note to myself, I just want to remind you that you are capable of
everything and not giving up so easily, remember there is always one
way, it is only to connect the dots. Never give up without fighting.
This may be too weird to happen to anyone else, but... Check your actually-imported packages. Mine looked like this:
Clearly, something borked on import here... removed and readded the correct "werkzeug" package and it "worked" (turns out I still need to implement one of the other solutions offered to this question... :-( )
Ah- but you ask: "how do I remove a corrupted package like this? The GUI won't let me!!". Fear not, that happened to me too. In Pycharm, find the package file location by hovering over the package name under the settings menu, go there in file explorer, and delete the folder and anything else like it. Then reinstall the package with the GUI.
If you or anyone who are doing some flask course about swagger that require restplus, Werkzeug. Please uninstall restplus and use restx instead since restplus is dead so any solutions that require downgrading Werkzeug or restplus OR typing some weird stuff that you can't understand, is just making another error.
Read this article about restx, it fairly similar to restplus.
Flask-restx article

from google.cloud import monitoring_v3 ImportError: cannot import name monitoring_v3

I am trying to utilize the Google Cloud Platform's Stack Driver API with the following Python/Flask code below...
view.py
import google.cloud
from google.cloud import monitoring_v3
# from google.cloud.monitoring_v3 import query
requirements.txt
Flask==0.12.2
oauth2client==2.0.1
google-api-python-client==1.6.2
facebookads==2.11.1
httplib2==0.10.3
enum==0.4.6
requests-toolbelt==0.8.0
google-cloud-storage==1.6.0
google-resumable-media==0.3.1
google-auth
google-cloud-monitoring==0.28.0
google-cloud
For whatever reason it can't seem to find the monitoring_v3 library as when whenever I run the code I am getting the following error...
from google.cloud import monitoring_v3
ImportError: cannot import name monitoring_v3
I have tried to update to google-cloud-monitoring==0.29.0 and that just churns out another non-related error.
I solved it by upgrading monitoring 0.29.0 to 1.1.0
pip install --upgrade google-cloud-monitoring
Latest version now available is 2.0.0
https://pypi.org/project/google-cloud-monitoring/
Could be a conflict (dependency or otherwise) between google-api-python-client and google-cloud*.
The former is a REST client which includes the monitoring API, the latter is gRPC based client.
Are you using 'google-api-python-client' for anything else? If no, try removing that?
Make sure your requirements.txt file is proper, and located in the source directory where you have the main.py.
If everything fails , copy a requirements.txt file from a working function , and replace the requirements modules in it (strangely this worked for me :P)

Google Drive OAuth2

I'm trying to sync between python and google drive with the following details:
Authorized JavaScript origins: http://localhost:8080
Authorized redirect URIs: http://localhost:8080/
I copied the json file to the directory and ran this code:
from pydrive.auth import GoogleAuth
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
and I got this error:
from oauth2client.locked_file import LockedFile
ImportError: No module named locked_file
Can you please help me?
Had the same issue.
It looks there was a change in the newest version of the oauth2client, v2.0.0, which broke compatibility with the google-api-python-client module, which now got fixed https://github.com/adrian-the-git/google-api-python-client/commit/2122d3c9b1aece94b64f6b85c6707a42cca8b093, so an upgrade of the google-api-python-client restores compatibility and make everything working again:
$ pip install --upgrade git+https://github.com/google/google-api-python-client

Cannot import 'BaseHTTPRequestHandler'

I want to create a web server using http.server module in Python. But when execute the code it shows an error ImportError: cannot import name 'BaseHTTPRequestHandler'
I have Python27 and Python34 both installed on the same system.

python import error "No module named appengine.ext"

after runing this code,I found import error:-
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class MainPage(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Hello, webapp World!')
application = webapp.WSGIApplication([('/', MainPage)],debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
how to use google.apengine.ext
import sys
sys.path.insert(1, '/Users/<username>/google-cloud-sdk/platform/google_appengine')
sys.path.insert(1, '/Users/<username>/google-cloud-sdk/platform/google_appengine/lib/yaml/lib')
sys.path.insert(1, 'lib')
if 'google' in sys.modules:
del sys.modules['google']
this solves the problems for me
It looks like the App Engine SDK is not installed, or at least the Python runtime cannot find it.
read and follow the instructions here: https://cloud.google.com/appengine/downloads#Google_App_Engine_SDK_for_Python
They tell you, how to install App Engine SDK for Python.
Try:
import google
print google.__path__
to see what exactly you're importing.
I had this same issue because I pip installed gcloud before downloading and installing the SDK. The pip install created a python package google which didn't contain the appengine submodule (which is found in the SDK folder). I uninstalled the gcloud and related packages. Then just pip installed the google-cloud-bigquery which is the only package I needed from gcloud. Everything works fine now.
I faced similar error while calling Google Analytics API using AWS Lambda.
Workaround from (Schweigi1) helped me.
import googleapiclient
from googleapiclient.discovery_cache.base import Cache
class MemoryCache(Cache):
_CACHE = {}
def get(self, url):
return MemoryCache._CACHE.get(url)
def set(self, url, content):
MemoryCache._CACHE[url] = content
Usage:
service = googleapiclient.discovery.build("analyticsreporting", "v4", http=http, credentials=credentials,cache=MemoryCache())
Hope this helps someone who is facing this issue in AWS Lambda.
First possible reason:
you don't install the python library in google cloud sdk, so you can run in cmd (as administrator):
gcloud components install app-engine-python.
Second possible reason:
your IDE is not success get into google libraries, they exist in:
C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine
or in:
C:\Users\[your user]\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine
You can see in attached link explain how to add these libraries to IDE external libraries: https://stackoverflow.com/a/24206781/8244338
I got this error in python:
from google.appengine.api import search
ImportError: No module named appengine.api
I thought this would be something along the similar lines of what is happening in this thread.
So, my solution was to run "dev_appserver.py 'your yaml file' ". I got this solution following the below links:
1) https://cloud.google.com/appengine/docs/standard/python/tools/using-local-server
2) https://www.youtube.com/watch?v=BdqUY8lCuBI
Hope this helps!
check if you named some file google.py :) in the same package, because this can shadow the import of google.appengine.ext. I had the same error:
python import error “No module named appengine.ext”
and deleteting the file solved the problem.

Categories