I found (and tried successfully) to pull the user emails using terminal but was wondering if anyone knew how to do it from python? My program needs to the file daily and I'm trying to automate it.
Here's what I have
import firebase_admin
from firebase_admin import credentials
cred = credentials.Certificate("cred file")
firebase_admin.initialize_app(cred)
emails = (firebase auth:export account_file.csv)
then I try and read it, but the auth:export line is where it breaks giving me a syntax error
emails = (firebase auth:export account_file.csv) is not a correct sintax in python.
Haven't used it, but this function seems to list firebase users:
firebase_admin.auth.list_users(page_token=None, max_results=1000, app=None)
Check documentation here.
Once you have all your users toghether in some variable like firebase_users, you'll need to export them to .csv.
import csv
with open('firebase_users.csv', 'w', newline='') as csvfile:
fieldnames = ['first_name', 'mail']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
for user in firebase_users:
writer.writerow(user)
Also check here for python csv package.
As I said, haven't tried it. I'll do it later to refresh any possible mistake.
Related
I am relatively new to perforce. I have been asked to look into a way to automate the process of user account creation through a script. That is because during each Term we have so far been going in manually and making accounts for each new student ourselves, a process that is incredibly tedious.
I think I have a reasonably clear idea of what some of the Python code for this may look like, in terms of reading data from the spreadsheet. However, I am unsure about the second part - actually creating user accounts and tying them to the Perforce server we have. How would I go about doing that? The other thing I am confused about is how to prevent duplicate users from being made?
Here is some code for the first part of the process.
import csv
# Read in user data from the CSV file
with open('user_data.csv', 'r') as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
first_name = row['First Name']
last_name = row['Last Name']
username = row['Username']
email = row['Email']
password = row['Default Password']
With the P4Python module you can create a user with the fetch_user and save_user functions:
import csv
from P4 import P4
# Read in user data from the CSV file
with open('user_data.csv', 'r') as csv_file, P4().connect() as p4:
reader = csv.DictReader(csv_file)
for row in reader:
user = p4.fetch_user(row['Username'])
user._email = row['Email']
user._fullname = row['First Name'] + ' ' + row['Last Name']
user._password = row['Default Password']
p4.save_user(user, '-f') # -f lets an admin modify another user
Usernames are unique in Perforce's database, so it is not possible to create duplicate usernames (with the above script the last username processed would simply overwrite any previous user with that name).
If you wanted different behavior (e.g. to raise an exception when an existing user is encountered) you could add code to check for an existing user before modifying it, using p4.run_users(row['Username']) in a try/except to verify that no user is returned.
I'm trying to write some basic code to retrieve the list of workspaces and write the response to a file. I thought that this could be dumped to a JSON file?
Thanks for any help/suggestions.
I have taken the sample .py file and reworked it to look like this -
# Install the smartsheet sdk with the command: pip install smartsheet-python-sdk
import smartsheet
import logging
import os.path
import json
# TODO: Set your API access token here, or leave as None and set as environment variable "SMARTSHEET_ACCESS_TOKEN"
access_token = None
print("Starting ...")
# Initialize client
smart = smartsheet.Smartsheet(access_token)
# Make sure we don't miss any error
smart.errors_as_exceptions(True)
# Log all calls
logging.basicConfig(filename='rwsheet.log', level=logging.INFO)
response = smart.Workspaces.list_workspaces(include_all=True)
workspaces = response.data
with open('data.json', 'w') as outfile:
json.dump(workspaces, outfile)
print("Done")
I'm not sure what issue you are facing, but I think you would have an issue with the json.dump(workspaces, outfile) line as the results of that workspaces variable is a list that you would need to iterate through to get through the data. Using that variable will just print out the pointer with something like this:
[<smartsheet.models.workspace.Workspace object at 0x10382a4e0>]
To work around this you would need to loop over the results of the variable and print them each out to a file. I found this post here about printing output to a file. The answer gives three approaches and I was able to get each of them to work with a loop iterating over the results.
One example:
import smartsheet
smar_client = smartsheet.Smartsheet(<ACCESS_TOKEN>)
response = smar_client.Workspaces.list_workspaces(include_all=True)
workspaces = response.data
with open('workspaces.json', 'w') as f:
for workspace in workspaces:
print(workspace, file=f)
Running this gave me a workspaces.json file in the same directory I ran my script from with the list of workspace objects.
I actually wanted my bookmarks for a text classifier .It needs data in .json format .So i want to know a python script which will retrieve data from the bookmarks directory and store it in a .json file.(I am using ubuntu)
Google Chrome already saves bookmarks in a form of JSON. Your question does not define what is desired outcome so here is a simple code to access and print the whole file of your saved bookmarks on Google Chrome Windows operating system. You will need to do some adjustments to the code as it is designed to run on Windows rather than Ubuntu as I do not have access to it at this moment.
import getpass
import json
user = getpass.getuser()
loc = "C:/Users/{}/AppData/Local/Google/Chrome/User Data/Default/Bookmarks.bak".format(user)
f = open(loc, encoding="utf8")
data = json.load(f)
print(data)
Edit:
import getpass
import json
user = getpass.getuser()
loc = "C:/Users/{}/AppData/Local/Google/Chrome/User Data/Default/Bookmarks.bak".format(user)
with open(loc, encoding="utf8") as f:
data = json.load(f)
for y in range(0,100):
try:
for x in data["roots"]["bookmark_bar"]["children"][y]["children"]:
print(x["url"])
except:
pass
Basic Situation
I currently have access to a salesforce page that has a 5000+ list of contacts. However, the page can only be loaded 25 contacts at a time and copying and pasting is unfeasible. Clicking a contact also gives other useful details but the general list is the most important. I don't have access to an admin portal; I only have viewing access to specific content such as contacts.
The link is structured as follows: https://example.force.com/example/_ui/search/ui/UnifiedSearchResults?offset=25&fpg=1cjmlvhdxsqly&str=epsilon-mu&sen=&fen=003&initialViewMode=detail&relatedListId=Contact&aId=_1527023282480&cookieParam=cookieParam1527023882485&tyme=1527023282485
My View
Question
Is there a method (such as python, bash script, url edit, web-scraping, etc.) to either download the list (as a .cvs or .txt) or make the list populate in its entirety for simple copy and paste?
To get the whole table into Excel I run this script. You will need to add in your login details and the table name.
import csv
from simple_salesforce import Salesforce
"""
Downloading the table
"""
# Logging in to SF and creating object
sf = Salesforce(
password='{{password}}', username='{{uName}}',
security_token='{{token}}',
client_id='TestingApp')
# Getting the field names
tableInfo = sf.{{tableName}}.describe()
tableFields = []
for x in tableInfo['fields']:
tableFields.append(x['name'])
hdrs = ', '.join(tableFields)
output = sf.query_all("SELECT " + hdrs + " FROM {{tableName}}")
headline = []
for key in output['records'][0]:
headline.append(key)
with open('C:\\temp\\Table.csv', 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames = headline)
writer.writeheader()
for record in output['records']:
writer.writerow(record)
I looked at the previous threads regarding this topic, but they have not helped solve the problem.
how to read password protected excel in python
How to open write reserved excel file in python with win32com?
I'm trying to open a password protected file in excel without any user interaction. I searched online, and found this code which uses win32com.client
When I run this, I still get the prompt to enter the password...
from xlrd import *
import win32com.client
import csv
import sys
xlApp = win32com.client.Dispatch("Excel.Application")
print "Excel library version:", xlApp.Version
filename,password = r"\\HRA\Myfile.xlsx", 'caa team'
xlwb = xlApp.Workbooks.Open(filename, Password=password)
I don't think that named parameters work in this case. So you'd have to do something like:
xlwb = xlApp.Workbooks.Open(filename, False, True, None, password)
See http://msdn.microsoft.com/en-us/library/office/ff194819.aspx for details on the Workbooks.Open method.
I recently discovered a Python library that makes this task simple.
It does not require Excel to be installed and, because it's pure Python, it's cross-platform too!
msoffcrypto-tool supports password-protected (encrypted) Microsoft Office documents, including the older XLS binary file format.
Install msoffcrypto-tool:
pip install msoffcrypto-tool
You could create an unencrypted version of the workbook from the command line:
msoffcrypto-tool Myfile.xlsx Myfile-decrypted.xlsx -p "caa team"
Or, you could use msoffcrypto-tool as a library. While you could write an unencrypted version to disk like above, you may prefer to create an decrypted in-memory file and pass this to your Python Excel library (openpyxl, xlrd, etc.).
import io
import msoffcrypto
import openpyxl
decrypted_workbook = io.BytesIO()
with open('Myfile.xlsx', 'rb') as file:
office_file = msoffcrypto.OfficeFile(file)
office_file.load_key(password='caa team')
office_file.decrypt(decrypted_workbook)
# `filename` can also be a file-like object.
workbook = openpyxl.load_workbook(filename=decrypted_workbook)
If your file size is small, you can probably save that as ".csv".
and then read
It worked for me :)
Openpyxl Package works if you are using linux system. You can use secure the file by setting up a password and open the file using the same password.
For more info:
https://www.quora.com/How-do-I-open-read-password-protected-xls-or-xlsx-Excel-file-using-python-in-Linux
Thank you so much for the great answers on this topic. Trying to collate all of it. My requirement was to open a bunch of password protected excel files ( all had same password ) so that I could do some more processing on those. Please find the code below.
import pandas as pd
import os
from xlrd import *
import win32com.client as w3c
import csv
import sys
from tempfile import NamedTemporaryFile
df_list=[]
# print(len(files))
for f in files:
# print(f)
if('.xlsx' in f):
xlwb = xlapp.Workbooks.Open('C:\\users\\files\\'+f, False, True, None, 'password')
temp_f = NamedTemporaryFile(delete=False, suffix='.csv')
temp_f.close()
os.unlink(temp_f.name)
xlwb.SaveAs(Filename=temp_f.name, FileFormat=xlCSVWindows)
df = pd.read_csv(temp_f.name,encoding='Latin-1') # Read that CSV from Pandas
df.to_excel('C:\\users\\files\\password_removed\\'+f)