Python - Download files from Share Point | Authentication token error - python

I am working on a report automation project, where I need to download excel files automatically from a share point location. I tried some examples referring to Python - Download files from SharePoint site but getting below error within imported library function. Please let me know, what I am missing here.
Error:
Traceback (most recent call last):
File "worklod_report.py", line 66, in
if ctxAuth.acquire_token_for_user(username='murali.pandiyan#xyz.com', password=pwd):
File "C:\Users\murali.pandiyan\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\office365\runtime\auth\authentication_context.py", line 18, in acquire_token_for_user
return self.provider.acquire_token()
File "C:\Users\murali.pandiyan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\office365\runtime\auth\saml_token_provider.py", line 57, in acquire_token
self.acquire_service_token(options)
File "C:\Users\murali.pandiyan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\office365\runtime\auth\saml_token_provider.py", line 88, in acquire_service_token
token = self.process_service_token_response(response)
File "C:\Users\murali.pandiyan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\office365\runtime\auth\saml_token_provider.py", line 119, in process_service_token_response
return token.text
AttributeError: 'NoneType' object has no attribute 'text'
Python code:
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
import getpass
if __name__ == '__main__':
ctxAuth = AuthenticationContext(url='https://internal.abc.net/sites/Compute/')
print("Enter Password:")
pwd=getpass.getpass()
if ctxAuth.acquire_token_for_user(username='murali.pandiyan#xyz.com', password=pwd):
ctx = ClientContext(settings['url'], ctxAuth)
print("Authentication is success")
else:
print(ctxAuth.get_last_error())

The following code snippet for your reference.
if __name__ == '__main__':
ctxAuth = AuthenticationContext('https://internal.abc.net/sites/Compute/')
print("Enter Password:")
pwd=getpass.getpass()
if ctxAuth.acquire_token_for_user('murali.pandiyan#xyz.com', pwd):
ctx = ClientContext(settings['url'], ctxAuth)
print("Authentication is success")
else:
print(ctxAuth.get_last_error())
Check the authentication source code here: authentication_context.py
And the source code of file download is here: file_operations.py

Related

TypeError: 'type' object is not subscriptable, error when creating an trading bot with python

I am creating a trading bot. I have 2 files a settings.json file and a main.py file.
my settings.json file :
`{
"username": "51410030",
"password": "s5p3GI1zY",
"server": "Alpari-MT5-Demo",
"mt5Pathway": "C://Program Files/Alpari MT5/terminal64.exe",
"symbols": ["USDJPY.a"],
"timeframe": "M30"
}
and my main.py file :
import json
import os
import mt5_interface
import strategy
# Function to import settings from settings.json
def get_project_settings(importFilepath):
# Test the filepath to sure it exists
if os.path.exists(importFilepath):
# Open the file
f = open(importFilepath, "r")
# Get the information from file
project_settings = json.load(f)
# Close the file
f.close()
project_settings = list(project_settings)
# Return project settings to program
return project_settings
else:
return ImportError
# Main function
if __name__ == '__main__':
# Set up the import filepath
import_filepath = "C:/Users/james/PycharmProjects/how_to_build_a_metatrader5_trading_bot_expert_advisor/settings.json"
# Import project settings
project_settings = get_project_settings(import_filepath)
# Start MT5
mt5_interface.start_mt5(project_settings["username"], project_settings["password"], project_settings["server"],
project_settings["mt5Pathway"])
# Initialize symbols
mt5_interface.initialize_symbols(project_settings["symbols"])
# Select symbol to run strategy on
symbol_for_strategy = project_settings['symbols'][0]
# Start strategy one on selected symbol
strategy.strategy_one(symbol=symbol_for_strategy, timeframe=project_settings['timeframe'],
pip_size=project_settings['pip_size'])
my prblem is when i run my main.py file it gives me this error:
Traceback (most recent call last):
File "i:\Traiding Bot\code\main.py", line 32, in <module>
mt5_interface.start_mt5(project_settings["username"], project_settings["password"], project_settings["server"],
TypeError: 'type' object is not subscriptable
please help me.
I couldn't find a solution please help me.
There are a few issues with your code:
You're trying to access fields in a list. That's not possible, you should keep your list a dictionary if you want access its fields.
You're returning an ImportError, if you want to raise an error, use raise ImportError("Your error message"). Or if you want to catch the error, use a try: <your code> except: return None and then check if you're returning None or not.

Create a Spotify playlist using spotipy

I am trying to create a playlist using the spotipy library. I followed the instructions on their website alongside this solved question Spotipy invalid username? . When running the code provided in this question (fitted to my Spotify developer account) everything works fine. However when trying another scope corresponding to my object of creating a playlist I get the same username error as mentioned in the linked question:
Traceback (most recent call last):
File "C:\Users\d92167\Spotify\Create_Favorites.py", line 23, in <module>
sp.user_playlist_create(cred.user_name, name=playlist_name)
File "C:\Users\d92167\Anaconda3\lib\site-packages\spotipy\client.py", line 784, in user_playlist_create
return self._post("users/%s/playlists" % (user,), payload=data)
File "C:\Users\d92167\Anaconda3\lib\site-packages\spotipy\client.py", line 302, in _post
return self._internal_call("POST", url, payload, kwargs)
File "C:\Users\d92167\Anaconda3\lib\site-packages\spotipy\client.py", line 267, in _internal_call
raise SpotifyException(
SpotifyException: https://api.spotify.com/v1/users/*My Username*/playlists:
Invalid username
My code:
import spotipy
import cred
scope = 'playlist-modify-public'
token = spotipy.util.prompt_for_user_token(cred.user_name,scope,client_id=cred.client_id,client_secret=cred.client_secret,redirect_uri=cred.redirect_url)
sp = spotipy.Spotify(auth=token)
playlist_name = 'Test'
sp.user_playlist_create(cred.user_name, name=playlist_name)
I am using Python 3.8 and Spotipy version 2.20.0
I have 2 possible solutions:
1: You forgot to type user=
sp.user_playlist_create(user=cred.user_name, name=playlist_name)
2: Maybe the user_name in the cred file is wrong. You can get the username with this code:
sp_user = sp.current_user()
user_name = sp_user['uri'].split(":")[2]

Unable to import a file in python

I want to import a file in a local directory but python refused to do so and it gives error everytime i do so.
I tried putting "from Admin_login import Admin_login" but it gives an error saying
"ModuleNotFoundError: No module named 'Admin_login'"
my code:-(main.py)
from .Admin_login import Admin_login
loggsin = Admin_login.login()
if loggsin == True:
print("You are logged in")
This is the Admin_login.py file
import json
import os
def load_data():
with open("data.json", "r") as f:
Data = json.load(f)
return Data
class Admin_login():
def login(self):
Login = False
while Login == False:
id = input("Enter the id you want to login = ")
data = load_data()
if id == data["id"]:
print(data["name"])
passord = input("Enter the password = ")
if passord == data["password"]:
print("You are successfully logged in")
Login = True
return Login
os.system('cls')
else:
print("The id doesn't exist... Please try again!")
Login = False
return Login
os.system('cls')
if __name__ == '__main__' :
Admin_login()
and the error it gives is :-
Traceback (most recent call last):
File "C:\Users\myUser\Desktop\LibApp\main.py", line 1, in <module>
from .Admin_login import Admin_login
ImportError: attempted relative import with no known parent package
pls help
My best guess is that the '.' is giving you the trouble. When you add a dot to a directory name, it is referring to a relative directory and not an absolute one. That's what that error you're getting is referring to. If those two files are in the same directory, you can just remove the dot and it should work.

Flink Python Datastream API Kafka Consumer

Im new to pyflink. Im tryig to write a python program to read data from kafka topic and prints data to stdout. I followed the link Flink Python Datastream API Kafka Producer Sink Serializaion. But i keep seeing NoSuchMethodError due to version mismatch. I have added the flink-sql-kafka-connector available at https://repo.maven.apache.org/maven2/org/apache/flink/flink-sql-connector-kafka_2.11/1.13.0/flink-sql-connector-kafka_2.11-1.13.0.jar. Can someone help me in with a proper example to do this? Following is my code
import json
import os
from pyflink.common import SimpleStringSchema
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.datastream.connectors import FlinkKafkaConsumer
from pyflink.common.typeinfo import Types
def my_map(obj):
json_obj = json.loads(json.loads(obj))
return json.dumps(json_obj["name"])
def kafkaread():
env = StreamExecutionEnvironment.get_execution_environment()
env.add_jars("file:///automation/flink/flink-sql-connector-kafka_2.11-1.10.1.jar")
deserialization_schema = SimpleStringSchema()
kafkaSource = FlinkKafkaConsumer(
topics='test',
deserialization_schema=deserialization_schema,
properties={'bootstrap.servers': '10.234.175.22:9092', 'group.id': 'test'}
)
ds = env.add_source(kafkaSource).print()
env.execute('kafkaread')
if __name__ == '__main__':
kafkaread()
But python doesnt recognise the jar file and throws the following error.
Traceback (most recent call last):
File "flinkKafka.py", line 31, in <module>
kafkaread()
File "flinkKafka.py", line 20, in kafkaread
kafkaSource = FlinkKafkaConsumer(
File "/automation/flink/venv/lib/python3.8/site-packages/pyflink/datastream/connectors.py", line 186, in __init__
j_flink_kafka_consumer = _get_kafka_consumer(topics, properties, deserialization_schema,
File "/automation/flink/venv/lib/python3.8/site-packages/pyflink/datastream/connectors.py", line 336, in _get_kafka_consumer
j_flink_kafka_consumer = j_consumer_clz(topics,
File "/automation/flink/venv/lib/python3.8/site-packages/pyflink/util/exceptions.py", line 185, in wrapped_call
raise TypeError(
TypeError: Could not found the Java class 'org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer'. The Java dependencies could be specified via command line argument '--jarfile' or the config option 'pipeline.jars'
What is the correct location to add the jar file?
I see that you downloaded flink-sql-connector-kafka_2.11-1.13.0.jar, but the code loades flink-sql-connector-kafka_2.11-1.10.1.jar.
May be you can have a check
just need to check the path to flink-sql-connector jar
You should add jar file of flink-sql-connector-kafka, it depends on your pyflink and scala version. If versions are true, check your path in add_jars function if the jar package is here.

Instabot API for Python raises error after running code for the 2nd time

I am currently working with the Instabot API for python and I ran across the following issue:
I wrote a small program:
from instabot import Bot
bot = Bot()
bot.login(username = "[my username]", password = "[my passowrd]")
bot.follow("lego")
which worked fine after running it for the very first time. However, after running the program for a second time, this time following another account, it raised an error ("KeyError: ds_user").
This error can be fixed by deleting the config folder inside the project folder. Unfortunately, this isn't a very sustainable solution, as it makes working on the code really arduous. I therefore would like to know if there is any solution for getting the program to run multiple times without having to delete the config folder over and over again.
I am receiving the following traceback (code is running in an anaconda environment called "Instagram Automation"):
Traceback (most recent call last):
File "e:/Programme/OneDrive/Dokumente/Projekte/Instagram Automation/main.py", line 4, in <module>
bot.login(username = "[my username]", password = "[my password]")
File "E:\Programme\Anaconda\envs\Instagram Automation\lib\site-packages\instabot\bot\bot.py", line 443, in login
if self.api.login(**args) is False:
File "E:\Programme\Anaconda\envs\Instagram Automation\lib\site-packages\instabot\api\api.py", line 240, in login
self.load_uuid_and_cookie(load_cookie=use_cookie, load_uuid=use_uuid)
File "E:\Programme\Anaconda\envs\Instagram Automation\lib\site-packages\instabot\api\api.py", line 199, in load_uuid_and_cookie
return load_uuid_and_cookie(self, load_uuid=load_uuid, load_cookie=load_cookie)
File "E:\Programme\Anaconda\envs\Instagram Automation\lib\site-packages\instabot\api\api_login.py", line 352, in load_uuid_and_cookie
cookie_username = self.cookie_dict["ds_user"]
KeyError: 'ds_user'
As far as I can see, the only way on your side to fight the symptoms is to always delete the JSON file in the config folder, e.g:
import os
if os.path.isfile("path/to/config/file.json"):
os.remove("path/to/config/file.json")
import instabot
# rest of your code goes here
The developers of instabot should fix the source of the problem, for example by using self.cookie_dict.get("ds_user", "some default value") instead of self.cookie_dict["ds_user"]

Categories

Resources