Why am I getting a keyerror when trying to import the requests module? KeyError: 'requests' - python-3.x

I don't understand why I am getting a KeyError. When running my code through the idle debugger.The directory with the requests module/folder is added to the PATH. Installing with pip shows that all of the dependencies are installed, and the module shows up when I run pip freeze. I'm not sure what the problem is here... Any help would be greatly appreciated.
import requests
def get_btc_price():
# Make the API call to retrieve the current price of Bitcoin
response = requests.get(
"https://api.kucoin.com/api/v1/market/orderbook/level2_100?symbol=BTC-USDT"
)
# Check if the API call was successful
if response.status_code == 200:
# Parse the JSON response
data = response.json()
# Return the current price of Bitcoin
return print(float(data["data"]["bids"][0][0]))
# If the API call was unsuccessful, return 0
return 0
get_btc_price

I think there was a conflict with an old version of Python... I deleted all PATH variables related to Python, then did an uninstall/reinstall of Python and the issue is resolved.

Related

ModuleNotFoundError: No module named 'rfc822'

I trying to read my email python version 3.6.9 and pip3 version 9.0.1. when i run the following script it returns the error shows below. I try to install rfc822 with pip and pip3. Can you please help me to solve this issue.
Many thanks Erik
ERROR
Traceback (most recent call last):
File "/home/webapp/git/RA Functions/test.py", line 3, in <module>
import rfc822
ModuleNotFoundError: No module named 'rfc822'
CODE
import poplib
import string, random
import rfc822
from io import StringIO
def readMail():
SERVER = "pop.gmail.com"
USER = "myemail#gmail.com"
PASSWORD = "mypassword"
# connect to server
server = poplib.POP3(SERVER)
# login
server.user(USER)
server.pass_(PASSWORD)
# list items on server
resp, items, octets = server.list()
for i in range(0,10):
id, size = string.split(items[i])
resp, text, octets = server.retr(id)
text = string.join(text, "\n")
file = StringIO.StringIO(text)
message = rfc822.Message(file)
for k, v in message.items():
print(k, "=", v)
readMail()
This module is deprecated since version 2.3: The email package should be used in preference to the rfc822 module. This module is present only to maintain backward compatibility, and has been removed in Python 3.
For more information visit this : Deprecated Link
But here is another module which is plone.rfc822
This package provides primitives for turning content objects described by zope.schema fields into RFC (2)822 style messages. It utilizes the Python standard library’s email module.
For installation: pip install plone.rfc822
For information visit this: Active Link

how to fix an error during uploading custom dataset in to colab?

I have followed all the steps described in most tutorials on how to upload your custom dataset into google colab. but I am getting an error which I try a lot to fix but not working.
I am trying to train a CNN model using my custom dataset. I try to upload it on colab using the code snippet given in most tutorials.
the following error is displayed when I run the code snippet
Downloading zip file
---------------------------------------------------------------------------
HttpError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/pydrive/files.py in FetchMetadata(self, fields, fetch_all)
236 fields=fields)\
--> 237 .execute(http=self.http)
238 except errors.HttpError as error:
6 frames
HttpError: <HttpError 404 when requesting https://www.googleapis.com/drive/v2/files/https%3A%2F%2Fdrive.google.com%2Fopen%3Fid%3D1RqLx88tx2FCV0Z3CHsqVtx7S3_ffE-UW?alt=json returned "File not found: https://drive.google.com/open?id=1RqLx88tx2FCV0Z3CHsqVtx7S3_ffE-UW">
During handling of the above exception, another exception occurred:
ApiRequestError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/pydrive/files.py in FetchMetadata(self, fields, fetch_all)
237 .execute(http=self.http)
238 except errors.HttpError as error:
--> 239 raise ApiRequestError(error)
240 else:
241 self.uploaded = True
ApiRequestError: <HttpError 404 when requesting https://www.googleapis.com/drive/v2/files/https%3A%2F%2Fdrive.google.com%2Fopen%3Fid%3D1RqLx88tx2FCV0Z3CHsqVtx7S3_ffE-UW?alt=json returned "File not found: https://drive.google.com/open?id=1RqLx88tx2FCV0Z3CHsqVtx7S3_ffE-UW">
#this is the code snippet I have taken from tutorials to upload dataset to google colab.
!pip install -U -q PyDrive
# Insert your file ID
# Get it by generating a share URL for the file
# An example : https://drive.google.com/file/d/1iz5JmTB4YcBvO7amj3Sy2_scSeAsN4gd/view?usp=sharing
zip_id = 'https://drive.google.com/open?id=1RqLx88tx2FCV0Z3CHsqVtx7S3_ffE-UW'
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
import zipfile, os
# 1. Authenticate and create the PyDrive client.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
if not os.path.exists('MODEL'):
os.makedirs('MODEL')
# 2. Download Zip
print ("Downloading zip file")
myzip = drive.CreateFile({'id': zip_id})
myzip.GetContentFile('model.zip')
# 3. Unzip
print ("Uncompressing zip file")
zip_ref = zipfile.ZipFile('model.zip', 'r')
zip_ref.extractall('MODEL/')
zip_ref.close()
OMG. after a long hour (almost 8 hours) researching on the internet and brainstorming i found the answer. if any one who is new working on colab and face a similar error here is how i solved this error. The problem on the above code is the way we assign the file id. zip_id = 'https://drive.google.com/open?id=1RqLx88tx2FCV0Z3CHsqVtx7S3_ffE-UW'. most of the tutorial I have seen told us just to take the file id by right clicking the file in google drive and copy the share link address. but the file id is not the whole thing we copied. the file id is only after the id= which is in my case 1RqLx88tx2FCV0Z3CHsqVtx7S3_ffE-UW. After giving this as an id the error is gone. Hope this response will help other colab starters.

Instagram API facing error

This is my code for Instagram API which I referred in some github. But I'm getting error while running on jupyter notebook using python language.
from instagram.client import InstagramAPI
access_token = "6784563950.xxxxxxx.32e0d729b8c741508fbbcba17f8a7e57"
client_secret = "863bb1767xxxxxxx34861c31efe54104ae"
api = InstagramAPI(access_token=access_token, client_secret=client_secret)
recent_media, next_ = api.user_recent_media(user_id="67xxxx3950", count=10)
for media in recent_media: print(media)
I'm getting error
"C:\Users\Balaji\Anaconda3\lib\site-packages\instagram\models.py in
object_from_dictionary(cls, entry)
97 new_media.comment_count = entry['comments']['count']
98 new_media.comments = []
---> 99 for comment in entry['comments']['data']:
100 new_media.comments.append(Comment.object_from_dictionary(comment))
101
KeyError: 'data'.
Can anyone help me with proper code? If I write print media it says put parenthesis.
Official client is deprecated since June 2016. Use a forked and maintained client like: https://github.com/MabrianOfficial/python-instagram
To install it pip install --upgrade git+https://github.com/MabrianOfficial/python-instagram

Dynamic database connection Flask-SQLAlchemy

i need to connect two database. the default database is fixed but the other one is dynamic, its based on URL.
for example if url is : yourapp.myweb.com then second database name will be yourapp
i try connect database into init.py but its show me following error
builtins.AssertionError
AssertionError: A setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.
To fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests.
here is my init.py
from flask import Flask,session
from flask_sqlalchemy import SQLAlchemy
import os
app = Flask(__name__,static_url_path='/static')
# Database Connection
database = request.url.split("/")[2].split(".")[0]
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root:root#localhost/main_database"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_BINDS'] = {
'user_db': 'mysql+pymysql://root:root#localhost/database_'+str(database), #dynamic Connection
}
db = SQLAlchemy(app)
db.create_all()
db.create_all(bind=['user_db'])
# db.init_app(app)
from . import views
here is the viwe.py
#app.route('/login', methods = ['GET'])
def index():
try:
from .model import Users
# Some Code
except Exception as e:
raise e
# return "Failed to login ! Please try again."
here is the model.py
from application import db
class Users(db.Model):
__bind_key__ = 'user_db'
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key = True)
email = db.Column(db.String(50))
name = db.Column(db.String(50))
password = db.Column(db.String())
def __repr__(self):
return '<User %r>' % self.name
As I said in one of my comments, this might be a problem with the database connection. Here's what I'd check for:
First of all, make sure you have the right engine installed in your virtual environment (you can check easily by running pip list; just in case, let me insist that libraries need to be installed in a virtual environment). Make sure you have not pymysql, but the port to Python3, called mysqlclient. pymysql only works with Python2. In order to install this library, you need to install first the Python and MySQL development headers. For example, in Debian/Ubuntu:
sudo apt-get install python-dev libmysqlclient-dev
Then you can install the library with the following command:
pip install mysqlclient
If this is installed, make sure you can actually connect to the database using the library. Open a Python shell within the virtual environment and type the following (from the example in github):
import pymysql.cursors
connection = pymysql.connect(host='<you_host>',
user='<user>',
password='<password>',
db='<database_name>',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
do_something()
except:
pass
If this works, make sure you're running the most recent version of Flask (0.12 at the moment; this again you can check by running pip list), as there are several bugs related to running Flask in DEBUG mode that have been fixed over time.
It's surely not the case here, but another sanity check is verifying that no other process is running on the port that you want to use for Flask.
If all of the above is working fine, I'd need to see a bit of the stack trace to figure out what is actually going on.

How to catch an ImportError non-recursively? (dynamic import)

Say we want to import a script dynamically, i.e. the name is constructed at runtime. I use this to detect plugin scripts for some program, so the script may not be there and the import may fail.
from importlib import import_module
# ...
subpackage_name = 'some' + dynamic() + 'string'
try:
subpackage = import_module(subpackage_name)
except ImportError:
print('No script found')
How can we make sure to only catch the possible import failure of the plugin script itself, and not of the imports that may be contained inside the plugin script?
Side note: this question is related, but is about static imports (using the import keyword), and the provided solutions don't work here.
Since Python 3.3, ImportError objects have had name and path attributes, so you can catch the error and inspect the name it failed to import.
try:
import_module(subpackage_name)
except ImportError as e:
if e.name == subpackage_name:
print('subpackage not found')
else:
print('subpackage contains import errors')
ImportErrors in Python have messages you can read name attributes you can use if you have the exception object:
# try to import the module
try:
subpackage = import_module(subpackage_name)
# get the ImportError object
except ImportError as e:
## get the message
##message=e.message
## ImportError messages start with "No module named ", which is sixteen chars long.
##modulename=message[16:]
# As Ben Darnell pointed out, that isn't the best way to do it in Python 3
# get the name attribute:
modulename=e.name
# now check if that's the module you just tried to import
if modulename==subpackage_name:
pass
# handle the plugin not existing here
else:
# handle the plugin existing but raising an ImportError itself here
# check for other exceptions
except Exception as e:
pass
# handle the plugin raising other exceptions here

Resources