Python - Accept CLI arguments and process it - python

I created a python script to save some data to a test database in firebase.
Here's my code:
from firebase import firebase
firebase = firebase.FirebaseApplication('https://www.somefirebaseapp.firebaseapp.com')
result = firebase.post('/data','test_data':'test123')
print(result)
It successfully inserted the data in the firebase console. Now I want to do this by running the python script via terminal (I'm using RPi), and add some arguments to save.
E.G
python3 firebase-save.py thisisatestdata
Which will make the code look like this:
result = firebase.post('/data','test_data':'inserted_argument_here')
How do I achieve this?

You can do this using click (or build in argparse) library
from firebase import firebase
import click
import ast
firebase = firebase.FirebaseApplication('https://www.somefirebaseapp.firebaseapp.com')
#click.command()
#click.option('--data', default='', help='Test data.')
def test(data):
try:
test_data= ast.literal_eval(data)
except ValueError:
pass
result = firebase.post('/data','test_data': test_data)
print(result)

import sys
from firebase import firebase
firebase = firebase.FirebaseApplication('https://www.somefirebaseapp.firebaseapp.com')
param_1= sys.argv[1]
result = firebase.post('/data','test_data':param_1)
print(result)

Related

Use python to execute shell command and redirect the output to a variable

I am trying to do 2 things with Python-
Execute a command at the terminal
Save the output of the above command to a variable.
This is my code till now -
import subprocess
ip_address = "http://ipwho.is/104.123.204.11"
query_reply = subprocess.run(["curl" , ip_address])
print("The exit code was: %d" % query_reply.returncode)
The query_reply only saves the return code as I am using query_reply.returncode. Whereas I want to save the general output of the command curl http://ipwho.is/104.123.204.11 to a variable.
This output is a dict-like structure -
{"ip":"104.123.204.11","success":true,"type":"IPv4","continent":"North America","continent_code":"NA","country":"United States","country_code":"US","region":"California","region_code":"CA","city":"San Jose","latitude":37.3382082,"longitude":-121.8863286,"is_eu":false,"postal":"95113","calling_code":"1","capital":"Washington D.C.","borders":"CA,MX","flag":{"img":"https:\/\/cdn.ipwhois.io\/flags\/us.svg","emoji":"\ud83c\uddfa\ud83c\uddf8","emoji_unicode":"U+1F1FA U+1F1F8"},"connection":{"asn":16625,"org":"Akamai Technologies, Inc.","isp":"Akamai Technologies, Inc.","domain":"gwu.edu"},"timezone":{"id":"America\/Los_Angeles","abbr":"PDT","is_dst":true,"offset":-25200,"utc":"-07:00","current_time":"2022-07-25T11:26:47-07:00"}}
The final goal is to access the fields like the region, city etc. inside the above structure. What is the general process to approach this sort of problem?
there is an arg to get output
import subprocess
import json
r = subprocess.run(["curl" , "http://ipwho.is/104.123.204.11"], capture_output=True)
djson = json.loads(r.stdout.decode())
djson["region"], djson["city"]
or better just querying it
import requests
with requests.get("http://ipwho.is/104.123.204.11") as response:
djson = response.json()
djson["region"], djson["city"]
You can use subprocess.check_output, which returns the subprocess output as a string:
import subprocess
import json
raw = subprocess.check_output(["curl", "http://ipwho.is/104.123.204.11"])
data = json.loads(raw)
print(data)
Although this works, it's rarely if ever a good idea to shell out to curl to retrieve a URL in Python. Instead, use the excellent requests library to get the URL directly:
import requests
req = requests.get("http://ipwho.is/104.123.204.11")
req.raise_for_status()
data = req.json()
print(data)
This is simpler, handles errors better (raise_for_status will raise an easy-to-understand exception if the server returns an error code), faster, and does not depend on the curl program being present.
(Note: although similar to the other answer, the code snippets in this answer should work directly without modification).

How to download a report as a CSV directly from Salesforce Lightning?

I am creating a Python script for downloading a report from Salesforce as a CSV.
My script is working perfectly fine for Salesforce Classic. However, I need to get it working for Lightning Experience. I'm using the simple-salesforce Python package to access our org. For SF Classic I enter a link that is structured like this: https://my-company.my.salesforce.com/my_report_id?view=d&snip&export=1&enc=UTF-8&xf=csv
The script is basically like this:
from simple-salesforce import Salesforce
import requests
import pandas as pd
import csv
from io import StringIO
sf = Salesforce(username="my_username", password="my_password",
security_token="my_token")
sf_org = "https://my_company.my.salesforce.com/"
report_id = "0000" # Some report id
sf_report_loc = "{0}{1}?view=d&snip&export=1&enc=UTF-8&xf=csv".format(sf_org, report_id)
response = requests.get(sf_report_loc, headers=sf.headers, cookies={"sid": sf.session_id})
new_report = response.content.decode("utf-8")
df = pd.read_csv(StringIO(new_report)) # Save the report to a DataFrame.
Whenever I switch to Lightning, the link is invalid and I get redirected. Is there a way to make this work in Lightning?
Try with isdtp parameter. In classic it was used to force view pages without sidebar or header, for example add isdtp=vw to a random page and see what happens.
https://my_company.my.salesforce.com/00O.....?isdtp=p1&export=1&enc=UTF-8&xf=csv ?
(no idea what's 'p1' but that's what I see in Chrome's download history as part of the report's source URL)

Download Tableau view using python

I am looking for a way to download a view of tableau using python. I'm able to login into tableau online via python and able to see listed workbooks and views.
as user doesn't have permission of workbook so can't able to download a workbook, but view I'm able to just entering in chrome but can't able to find a way using python. also i want to save the view in pandas dataframe.
if there is anyway to do the above, kindly let me know?
# coding=utf-8
import tableauserverclient as TSC
import argparse
import requests
import pandas as pd
import csv
parser = argparse.ArgumentParser()
args = parser.parse_args()
tableau_auth = TSC.TableauAuth('admin', 'admin', site_id='test')
server = TSC.Server('https://10az.online.tableau.com')
server.auth.sign_in(tableau_auth)
# print(server.projects.get())
with server.auth.sign_in(tableau_auth):
all_workbooks, pagination_item = server.workbooks.get()
print("\nThere are {} workbooks on site: ".format(pagination_item.total_available))
print([workbook.name for workbook in all_workbooks])
if all_workbooks:
sample_workbook = all_workbooks[3]
server.workbooks.populate_views(sample_workbook)
print("\nName of views in {}: ".format(sample_workbook.name))
print([view.name for view in sample_workbook.views])
print([view.id for view in sample_workbook.views])
server.workbooks.populate_connections(sample_workbook)
print("\nConnections for {}: ".format(sample_workbook.name))
print(["{0}({1})".format(connection.id, connection.datasource_name)
for connection in sample_workbook.connections])
view_id = 'ddd'
server_url = 'https://10az.online.tableau.com'
src_url = "https://10az.online.tableau.com/#/site/abc/views/test/AccountAdvertisersList.csv" \
.format(server_url, server.version, server.site_id, view_id)
# path = server.workbooks.download(sample_workbook.id)

Updating a single value in Firebase with python

I am a total newbie when it comes to backend. I am working on a very simple webpage that needs one element to be updated every couple minutes or so. I'd like it to make a request to my Firebase database, get a single integer, and change a number on the webpage to that integer.
Right now I am having trouble updating the Firebase with a simple Python program. Here is what my Firebase looks like every time I run my python script: Click
When I run the script, it adds 6 new random variables with the value I'd like to send to Firebase. Here is what my code looks like so far:
from firebase import firebase
fb = firebase.FirebaseApplication('https://myAssignedDomain.com/', None)
Result = fb.post('test/coffee', {'percentage': 40})
What do I need to do in order to only change one existing value in Firebase rather than create 6 new random variables?
This is how you can update the value of a particular property in firebase python 1.2 package
from firebase import firebase
fb = firebase.FirebaseApplication('https://myAssignedDomain.com/', None)
fb.put('test/asdf',"count",4) #"path","property_Name",property_Value
This function will update the 'percentage' value from your node. Just make sure that the node is writable so your script can modify it.
import urllib.request
import urllib.error
import json
def update_entry(new_percentage):
my_data = dict()
my_data["percentage"] = new_percentage
json_data = json.dumps(my_data).encode()
request = urllib.requests.Request("https://<YOUR-PROJECT-ID>.firebaseio.com/test/coffe.json", data=json_data, method="PATCH")
try:
loader = urllib.request.urlopen(request)
except urllib.error.URLError as e:
message = json.loads(e.read())
print(message["error"])
else:
print(loader.read())

Python script to follow Twitter user IDs

I am trying to create a little python script to follow Twitter user IDs from a textfile (one per line, in numeric format e.g. 217275660, 30921943, etc.). I took a look at this answer on stack exchange to make the code below using the 'try/except' answer, but I am getting an error "NameError: name 'TwitterError' is not defined"...
Anyone know how to clear this issue up and fix the code? I feel like it should be pretty simple but haven't used the Twitter API before.
# Script to follow Twitter users from text file containing user IDs (one per line)
# Header stuff I've just thrown in from another script to authenticate
import json
import time
import tweepy
import pprint
from tweepy.parsers import RawParser
from auth import TwitterAuth
from datetime import datetime
auth = tweepy.OAuthHandler(TwitterAuth.consumer_key, TwitterAuth.consumer_secret)
auth.set_access_token(TwitterAuth.access_token, TwitterAuth.access_token_secret)
rawParser = RawParser()
api = tweepy.API(auth_handler = auth, parser = rawParser)
# Follow everyone from list?!
with open('to_follow.txt') as f:
for line in f:
try:
api.CreateFriendship(userID)
except TwitterError:
continue
print "Done."
That is may be because the tweepy throws error of type TweepError so you need to catch TweepError instead of TwitterError
for line in f:
try:
api.CreateFriendship(userID)
except TweepError,e:
continue

Categories

Resources