Adding strings from python to text file and then verify lines in while loop - python-3.7

I'm new to coding and still learning about Python.
I have a task where I have to upload lines from Python to a text file and then verify the lines later in the code e.g. I have to input user names and user passwords and add to the text file as [user_name, user_pass].
My problem is that when I try to verify the line one of 2 things happen. After I added a split function for the line e.g. verified_user, verified_password = line.split(", ") it runs into an error stating that I do not have enough values for the request made e.g 2 expected, 1 made. If I change the split input and it does run, the verification loop states that my inputs does not match any lines in the string.
Every thing works if I add the information to the text file only. But the moment I add via the appendix action in Python it no longer works.
this is what I have so far:
user_list = []
all_names_entered = "no"
while all_names_entered == "no":
user_name = input("Enter user name: ")
user_pass = input("Enter password: ")
user_list.append(user_name + ", " + user_pass)
while True:
all_names_entered = input("All users entered?: ")
if all_names_entered in ['yes','no']:
break
else:
print( 'please answer with yes or no' )
for items in user_list:
with open('user.txt', 'a') as file:
file.write(f"{user_name}, {user_pass}\n")
print (user_list)
file.close()
the next block reads as follow:
user_file = open("user.txt", "r+")
login = False
while login == False:
username = input("Enter user name: ")
password = input("Enter user password: ")
for line in user_file:
other = line.strip()
valid_user, valid_password = line.split(", ")
if username == valid_user and password == valid_password:
login = True
print ("You have successfully logged in")
break
else:
print("You have entered incorrect detail. Please try again")
user_file.seek(0)
user_file.close()

Firstly, indentation is important in Python.
Secondly, you're supposed to loop if user enters 'no'.
Utilize the item that's initialized in each for loop.
You initialized other but it was never consumed.
Following is code for writing into file:
user_list = []
all_names_entered = "no"
while all_names_entered == "no":
user_name = input("Enter user name: ")
user_pass = input("Enter password: ")
user_list.append(user_name + ", " + user_pass)
query_all_names_entered = True
while query_all_names_entered:
all_names_entered = input("All users entered?: ")
if all_names_entered == 'yes':
query_all_names_entered = False
break
elif all_names_entered == 'no':
query_all_names_entered = False
continue
else:
print('Please answer with yes or no')
all_names_entered = "no"
with open('user.txt', 'a') as file:
for item in user_list:
file.write(f"{item}\n")
print (user_list)
file.close()
And following is for reading file to log in:
user_file = open("user.txt", "r+")
login = False
lines = user_file.readlines()
while login == False:
username = input("Enter user name: ")
password = input("Enter user password: ")
for line in lines:
valid_user, valid_password = line.strip().split(", ")
if username == valid_user and password == valid_password:
login = True
print ("You have successfully logged in")
break
if login == False: print ("You have entered incorrect detail. Please try again")
user_file.close()

Related

Item does not have a file (error 500) when uploading a PNG file to a portal using add item method

I am trying to setup a POST request method using the "Add Item" operation within a REST API for my portal so that the PNG images can be add and later updated. Currently my script uploads the item to the portal but when i try to download the file or share it then it opens a page saying "Item does not have a file . Error 500" I assume its something to do with how i am building the POST request. How should i send the file over the POST request so that i can later download and update the file . Here is my current code:
def add_item(username,files,type,title):
"""
Add an item to the portal
Input:
- file: path of the the file to be uploaded
- username: username of user uploads the item
Return:
- Flag with a list of messages
"""
# set request header authorization type
header = {
'Authorization': f'Bearer {token}'
}
# build url
u_rl = f"{portal}/sharing/rest/content/users/{username}/addItem"
# search for id
req = requests.post(url=u_rl, headers=header,files=files,data={ "type":type,"title":title,"f": "json"})
response = json.loads(req.text)
if 'error' in response.keys():
error = response["error"]
raise Exception(
f"Error message: {error['message']}", f"More details: {','.join(error['details'])}")
return response["success"] if 'success' in response.keys() else False
if __name__ == "__main__":
user = input("input your USERNAME: ")
password = getpass.getpass("input your PASSWORD: ")
portal = "https://cvc.portal"
token = generate_token(user, password, portal=portal)
files = {'upload_file': open(r'C:\Users\test.png','rb')}
type='Image',
title='An image'
add_item(user,files,type,title

How to save each forloop output into separated file name not in a single file name?

I want to save each output of "forloop" into different text file, not in a single text file. Like for example. First loop output will be in Device1_Output01.txt, Second loop output
will be in Device2_Output02.txt, Device3_Output03.txt, etc. Please help me I'm a beginner. Appreciate your help in advance. Thank you.
import paramiko
import time
import sys
c = open("Command_List.txt", "r")
command_list = c.read().split("\n") /*Create a List from Command_List file */
d = open("Device_List.txt", "r")
nodes = d.read().split("\n") /*Create a List from Device_List file */
port = 22
username = "user"
password = "password"
for ip in nodes: /*Loop each ip in hosts list */
print("Login to:", ip)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port, username, password)
comm = ssh.invoke_shell()
for command in command_list: /*Loop each commmand in command_list
comm.send(' %s \n' %command)
time.sleep(.5)
output = comm.recv(9999)
output = output.decode('ascii').split(',') /*Convert string to List without any change*/
restorepoint = sys.stdout
sys.stdout = open('HWOutput.txt', "a") /*All output will be appended here. How will I save each forloop output into different filenames?.*/
print(''.join(output))
sys.stdout = restorepoint
ssh.close()
Just replace sys.stdout with an actual open file at the start of the loop, then close the file and revert back to initial stdout at the end.
for ip in nodes:
if not ip.strip(): continue
with open(ip + ".ssh-log.txt","wt") as sshlog:
sys.stdout = sshlog
print("Login to:", ip)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port, username, password)
comm = ssh.invoke_shell()
for command in command_list:
comm.send(' %s \n' %command)
time.sleep(.5)
output = comm.recv(9999)
output = output.decode('ascii').split(',')
print(''.join(output))
sys.stdout = sys.__stdout__
ssh.close()

py.test capture unhandled exception

We are using py.test 2.8.7 and I have the below method which creates a separate log file for every test-case. However this does not handle unhandled Exceptions. So if a code snippet throws an Exception instead of failing with an assert, the stack-trace of the Exception is not logged into the separate file. Can someone please help me in how I could capture these Exceptions?
def remove_special_chars(input):
"""
Replaces all special characters which ideally shout not be included in the name of a file
Such characters will be replaced with a dot so we know there was something useful there
"""
for special_ch in ["/", "\\", "<", ">", "|", "&", ":", "*", "?", "\"", "'"]:
input = input.replace(special_ch, ".")
return input
def assemble_test_fqn(node):
"""
Assembles a fully-qualified name for our test-case which will be used as its test log file name
"""
current_node = node
result = ""
while current_node is not None:
if current_node.name == "()":
current_node = current_node.parent
continue
if result != "":
result = "." + result
result = current_node.name + result
current_node = current_node.parent
return remove_special_chars(result)
# This fixture creates a logger per test-case
#pytest.yield_fixture(scope="function", autouse=True)
def set_log_file_per_method(request):
"""
Creates a separate file logging handler for each test method
"""
# Assembling the location of the log folder
test_log_dir = "%s/all_test_logs" % (request.config.getoption("--output-dir"))
# Creating the log folder if it does not exist
if not os.path.exists(test_log_dir):
os.makedirs(test_log_dir)
# Adding a file handler
test_log_file = "%s/%s.log" % (test_log_dir, assemble_test_fqn(request.node))
file_handler = logging.FileHandler(filename=test_log_file, mode="w")
file_handler.setLevel("INFO")
log_format = request.config.getoption("--log-format")
log_formatter = logging.Formatter(log_format)
file_handler.setFormatter(log_formatter)
logging.getLogger('').addHandler(file_handler)
yield
# After the test finished, we remove the file handler
file_handler.close()
logging.getLogger('').removeHandler(file_handler)
I have ended-up with a custom plugin:
import io
import os
import pytest
def remove_special_chars(text):
"""
Replaces all special characters which ideally shout not be included in the name of a file
Such characters will be replaced with a dot so we know there was something useful there
"""
for special_ch in ["/", "\\", "<", ">", "|", "&", ":", "*", "?", "\"", "'"]:
text = text.replace(special_ch, ".")
return text
def assemble_test_fqn(node):
"""
Assembles a fully-qualified name for our test-case which will be used as its test log file name
The result will also include the potential path of the log file as the parents are appended to the fqn with a /
"""
current_node = node
result = ""
while current_node is not None:
if current_node.name == "()":
current_node = current_node.parent
continue
if result != "":
result = "/" + result
result = remove_special_chars(current_node.name) + result
current_node = current_node.parent
return result
def as_unicode(text):
"""
Encodes a text into unicode
If it's already unicode, we do not touch it
"""
if isinstance(text, unicode):
return text
else:
return unicode(str(text))
class TestReport:
"""
Holds a test-report
"""
def __init__(self, fqn):
self._fqn = fqn
self._errors = []
self._sections = []
def add_error(self, error):
"""
Adds an error (either an Exception or an assertion error) to the list of errors
"""
self._errors.append(error)
def add_sections(self, sections):
"""
Adds captured sections to our internal list of sections
Since tests can have multiple phases (setup, call, teardown) this will be invoked for all phases
If for a newer phase we already captured a section, we override it in our already existing internal list
"""
interim = []
for current_section in self._sections:
section_to_add = current_section
# If the current section we already have is also present in the input parameter,
# we override our existing section with the one from the input as that's newer
for index, input_section in enumerate(sections):
if current_section[0] == input_section[0]:
section_to_add = input_section
sections.pop(index)
break
interim.append(section_to_add)
# Adding the new sections from the input parameter to our internal list
for input_section in sections:
interim.append(input_section)
# And finally overriding our internal list of sections
self._sections = interim
def save_to_file(self, log_folder):
"""
Saves the current report to a log file
"""
# Adding a file handler
test_log_file = "%s/%s.log" % (log_folder, self._fqn)
# Creating the log folder if it does not exist
if not os.path.exists(os.path.dirname(test_log_file)):
os.makedirs(os.path.dirname(test_log_file))
# Saving the report to the given log file
with io.open(test_log_file, 'w', encoding='UTF-8') as f:
for error in self._errors:
f.write(as_unicode(error))
f.write(u"\n\n")
for index, section in enumerate(self._sections):
f.write(as_unicode(section[0]))
f.write(u":\n")
f.write((u"=" * (len(section[0]) + 1)) + u"\n")
f.write(as_unicode(section[1]))
if index < len(self._sections) - 1:
f.write(u"\n")
class ReportGenerator:
"""
A py.test plugin which collects the test-reports and saves them to a separate file per test
"""
def __init__(self, output_dir):
self._reports = {}
self._output_dir = output_dir
#pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(self, item, call):
outcome = yield
# Generating the fully-qualified name of the underlying test
fqn = assemble_test_fqn(item)
# Getting the already existing report for the given test from our internal dict or creating a new one if it's not already present
# We need to do this as this method will be invoked for each phase (setup, call, teardown)
if fqn not in self._reports:
report = TestReport(fqn)
self._reports.update({fqn: report})
else:
report = self._reports[fqn]
result = outcome.result
# Appending the sections for the current phase to the test-report
report.add_sections(result.sections)
# If we have an error, we add that as well to the test-report
if hasattr(result, "longrepr") and result.longrepr is not None:
error = result.longrepr
error_text = ""
if isinstance(error, str) or isinstance(error, unicode):
error_text = as_unicode(error)
elif isinstance(error, tuple):
error_text = u"\n".join([as_unicode(e) for e in error])
elif hasattr(error, "reprcrash") and hasattr(error, "reprtraceback"):
if error.reprcrash is not None:
error_text += str(error.reprcrash)
if error.reprtraceback is not None:
if error_text != "":
error_text += "\n\n"
error_text += str(error.reprtraceback)
else:
error_text = as_unicode(error)
report.add_error(error_text)
# Finally saving the report
# We need to do this for all phases as we don't know if and when a test would fail
# This will essentially override the previous log file for a test if we are in a newer phase
report.save_to_file("%s/all_test_logs" % self._output_dir)
def pytest_configure(config):
config._report_generator = ReportGenerator("result")
config.pluginmanager.register(config._report_generator)

Authlib fetch_token issue

when i attempt to run following :
from authlib.integrations.requests_client import OAuth2Session
APPCLIENTID=os.getenv('AppClientId')
APPCLIENTSECRET=os.getenv('AppClientSecret')
USERNAME2=os.getenv("Username2")
PASSWORD2=os.getenv("Password222")
scope = 'openid email profile'
token_endpoint = 'https://api-product-test99.auth.eu-west-1.amazoncognito.com/oauth/token'
client = OAuth2Session(APPCLIENTID, APPCLIENTSECRET, scope=scope) #, redirect_uri="https://localhost/callback"
ar = 'https://localhost/callback?code=xxxxxx&state=xxxxx'
token = client.fetch_token(token_endpoint, authorization_response=ar)
print(token)
i get the message :
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
im just following the example on the Authlib page.
Am I missing something ?

Traceback after looping through all available news article

I am making a python CLI utility that will answer questions like "15 + 15" or "How many letters are in the alphabet".
I then decided to add the ability to search up the latest news using the newspaper module.
All of it works except when the for loop finishes, after printing a string literal, it gives me a error that I do not know what the heck it means.
Can someone decipher the error for me and if possible, help me fix the error? Thanks.
import requests
import wolframalpha
import wikipedia
import time
import sys
from threading import Thread
from newspaper import Article
import bs4
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen
version = 2.1
build = '19w12a6'
ready = 0
loadingAnimationStop = 0
appId = 'CENSORED STUFF BECAUSE I DON\'T WANT ANYONE TO TOUCH MY KEY'
client = wolframalpha.Client(appId)
exitNow = 0
def loadingAnimation():
while exitNow == 0:
print("Loading: |", end='\r')
time.sleep(0.2)
while ready == 1:
time.sleep(0)
print("Loading: /", end='\r')
time.sleep(0.2)
while ready == 1:
time.sleep(0)
print("Loading: -", end='\r')
time.sleep(0.2)
while ready == 1:
time.sleep(0)
sys.stdout.write("Loading: \ \r")
time.sleep(0.2)
while ready == 1:
time.sleep(0)
hui = Thread(target = loadingAnimation, args=())
hui.start()
def search_wiki(keyword=''):
searchResults = wikipedia.search(keyword)
if not searchResults:
print("No result from Wikipedia")
return
try:
page = wikipedia.page(searchResults[0])
except wikipedia.DisambiguationError:
page = wikipedia.page(err.options[0])
wikiTitle = str(page.title.encode('utf-8'))
wikiSummary = str(page.summary.encode('utf-8'))
print(' ', end='\r')
print(wikiTitle)
print(wikiSummary)
def search(text=''):
res = client.query(text)
if res['#success'] == 'false':
ready = 1
time.sleep(1)
print('Query cannot be resolved')
else:
result = ''
pod0 = res['pod'][0]
pod1 = res['pod'][1]
if (('definition' in pod1['#title'].lower()) or ('result' in pod1['#title'].lower()) or (pod1.get('#primary','false') == 'True')):
result = resolveListOrDict(pod1['subpod'])
ready = 1
time.sleep(0.75)
print(' ', end='\r')
print(result)
question = resolveListOrDict(pod0['subpod'])
question = removeBrackets(question)
#primaryImage(question)
else:
question = resolveListOrDict(pod0['subpod'])
question = removeBrackets(question)
search_wiki(question)
def removeBrackets(variable):
return variable.split('(')[0]
def resolveListOrDict(variable):
if isinstance(variable, list):
return variable[0]['plaintext']
else:
return variable['plaintext']
#def primaryImage(title=''):
# url = 'http://en.wikipedia.org/w/api.php'
# data = {'action':'query', 'prop':'pageimages','format':'json','piprop':'original','titles':title}
# try:
# res = requests.get(url, params=data)
# key = res.json()['query']['pages'].keys()[0]
# imageUrl = res.json()['query']['pages'][key]['original']['source']
# print(imageUrl)
# except Exception:
# print('Exception while finding image:= '+str(err))
page = requests.get('https://www.wolframalpha.com/')
s = page.status_code
if (s != 200):
ready = 1
time.sleep(1)
print('It looks like https://www.wolframalpha.com/ is not online.')
print('Please check your connection to the internet and https://www.wolframalpha.com/')
print('Stopping Python Information Engine')
while True:
time.sleep(1)
page = requests.get('https://www.wikipedia.org/')
s = page.status_code
if (s != 200):
ready = 1
time.sleep(1)
print('It looks like https://www.wikipedia.org/ is not online.')
print('Please check your connection to the internet and https://www.wikipedia.org/')
print('Stopping Python Information Engine')
while True:
time.sleep(1)
ready = 1
while exitNow == 0:
print('================================================================================================')
print('Python Information Engine CLI Version', end=' ')
print(version)
print('Create by Unsigned_Py')
print('================================================================================================')
ready = 1
time.sleep(1)
print(' ', end='\r')
print(' ', end='\r')
q = input('Search: ')
print('================================================================================================')
if (q == 'Credits()'):
print('Credits')
print('================================================================================================')
print('PIE is made by Unsigned_Py')
print('Unsigned_Py on the Python fourms: https://python-forum.io/User-Unsigned-Py')
print('Contact Unsigned_Py: Ckyiu#outlook.com')
if (q == 'Latest News'):
print('DISCLAIMER: The Python Information Engine News port is still in DEVELOPMENT!')
print('Getting latest news links from Google News...')
ready = 0
news_url = "https://news.google.com/news/rss"
Client = urlopen(news_url)
xml_page = Client.read()
Client.close()
soup_page = soup(xml_page,"xml")
news_list = soup_page.findAll("item")
ready = 1
print('================================================================================================')
article_number = 1
for news in news_list:
print(article_number, end=': ')
print(news.title.text)
print(news.pubDate.text)
if (input('Read (Y or N)? ') == 'y'):
ready = 0
url = news.link.text
article = Article(url)
article.download()
article.parse()
article.nlp()
ready = 1
print('================================================================================================')
print(article.summary)
print('================================================================================================')
article_number = article_number + 1
print("That's all for today!")
if (q == 'Version()'):
print('Python Information Engine CLI Version', end=' ')
print(version)
print('Running Build', end=' ')
print(build)
print('Upon finding a bug, please report to Unsigned_Py and I will try to fix it!')
print('Looking for Python Information Engine CLI Version 1.0 - 1.9?')
print("It's called Wolfram|Alpha and Wikipedia Engine Search!")
if (q != 'Exit()'):
if (q != 'Credits()'):
if (q != 'News'):
if (q != 'Version()'):
ready = 0
search(q)
else:
exitNow = 1
print('Thank you for using Python Information Engine')
print('================================================================================================')
time.sleep(2)
ready = 0
Here's the error:
Traceback (most recent call last):
File "C:\Users\ckyiu\OneDrive\Desktop\Python Information Engine 2.1.py", line 210, in <module>
search(q)
File "C:\Users\ckyiu\OneDrive\Desktop\Python Information Engine 2.1.py", line 62, in search
res = client.query(text)
File "C:\Users\ckyiu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wolframalpha\__init__.py", line 56, in query
return Result(resp)
File "C:\Users\ckyiu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wolframalpha\__init__.py", line 178, in __init__
super(Result, self).__init__(doc)
File "C:\Users\ckyiu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wolframalpha\__init__.py", line 62, in __init__
self._handle_error()
File "C:\Users\ckyiu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wolframalpha\__init__.py", line 69, in _handle_error
raise Exception(template.format(**self))
Exception: Error 0: Unknown error
Well I got it to work now, for some reason I put: if (q != 'News'): I wanted if (q != 'Latest News'):.
Then python threw me a error for that. I got it to work at least now.