问题
I am running code using Azure SDK.
First, I download the sdk by pip install azure
. Then I write to run the following python code.
import requests
import os
# make sure you configure these three variables correctly before you try to run the code
AZURE_ENDPOINT_URL='https://login.microsoftonline.com/xxxxxx-xx-155715822801/oauth2/token'
AZURE_APP_ID='6dxxxxx8-c4af-4522xxx6-5a8f8155a616'
AZURE_APP_SECRET='password'
def get_token_from_client_credentials(endpoint, client_id, client_secret):
payload = {
'grant_type': 'client_credentials',
'client_id': client_id,
'client_secret': client_secret,
'resource': 'https://management.core.windows.net/',
}
response = requests.post(endpoint, data=payload).json()
return response['access_token']
# test
if __name__ == '__main__':
auth_token = get_token_from_client_credentials(endpoint=AZURE_ENDPOINT_URL,
client_id=AZURE_APP_ID,
client_secret=AZURE_APP_SECRET)
print auth_token
After running the code, I got the message as follows.
File "D:\Python27\lib\site-packages\requests\__init__.py", line 58, in <module>
from . import utils
File "D:\Python27\lib\site-packages\requests\utils.py", line 26, in <module>
from .compat import parse_http_list as _parse_list_header
File "D:\Python27\lib\site-packages\requests\compat.py", line 39, in <module>
import cookielib
File "D:\Python27\lib\cookielib.py", line 32, in <module>
import re, urlparse, copy, time, urllib
File "C:\Users\yulei\Desktop\copy.py", line 8, in <module>
import azure.mgmt.compute
File "D:\Python27\lib\site-packages\azure\mgmt\compute\__init__.py", line 19, in <module>
from .computemanagement import *
File "D:\Python27\lib\site-packages\azure\mgmt\compute\computemanagement.py", line 23, in <module>
from requests import Session, Request
ImportError: cannot import name Session
回答1:
It seems that the issue was caused by the package requests
as the same name as the python file or directory includes file __init__.py
at the current directory.
Because Python imports packages in order from the paths sys.path
, and the first path is ''
(current directory).
So if you create a python file requests.py
or create a dir requests
include a file __init__.py
, Python firstly imports it as the package requests
. Then, running the code from requests import Session
will cause the error ImportError: cannot import name Session
.
Please check the current directory or dirs in the paths sys.path
in order and remove the file named requests.py
or the dir named requests
.
回答2:
I had recently upgraded my requests
library using sudo (sudo pip install --upgrade requests
), and then I was surprised that I couldn't just call the code without sudo.
It couldn't locate the files it just upgraded due to a permissions issue!
来源:https://stackoverflow.com/questions/34781904/importerror-cannot-import-name-session-when-using-azure-sdk